我想在 iframe 中加载外部网站,如果这些网站中的任何一个使用了框架阻止程序,那么我想将用户重定向到错误页面。为此提出了一些建议的方法:
- 等待加载超时
- 加载后查看 iframe src html 内容是否为“空”
- try catch 错误
- 维护“黑名单”网址数据库
到目前为止,令人沮丧的是,我在最后一项上运气最好。由于以下原因,其他方法不起作用:
- 等待加载超时:
- 即使使用帧 killer 的网站也会触发 onload 事件。例如,如果我尝试访问 www.google.com,它只会加载空的 html 结构。
- 加载后查看 iframe src html 内容是否为“空”
- 由于同源政策,您无法访问 iframe 的外部 src 内容。
- try catch 错误:
- 据我了解,我只能找到与本地 JS 代码引起的错误相关的错误处理函数,而没有与
"Refused to display <URL> in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'
等错误相关的任何内容。/'DENY'"
.
- 据我了解,我只能找到与本地 JS 代码引起的错误相关的错误处理函数,而没有与
- 维护“黑名单”网址数据库:
- 这显然是一个糟糕的解决方案,它不全面,而且 list 很大,哈哈。
也许我误解了其中一种方法。我这里缺少解决方案吗?对于上下文,我主要在 JS + jQuery 中执行此操作。
最佳答案
我有一个临时修复程序,按照@charlietfl的建议使用 header 信息,尽管它并不完美,正如您在测试部分中看到的那样,并非所有网站都在 header 中列出了 x-frame 选项。
<?php
// checkXFO
// checks x-frame options
// $headers: an array of headers
// returns: nothing
function checkXFO($headers){
if($headers['X-Frame-Options']==""){
echo "good to embed! <p>";
}
else{
echo "Denied! <p>";
}
}
//-----------------------
// tests
//-----------------------
// x-frame option: SAMEORIGIN
// should deny
// > passes
$headerArray = get_headers('http://www.google.com',1);
checkXFO($headerArray);
// x-frame option: DENY
// should deny
// > passes
$headerArray = get_headers('http://www.facebook.com',1);
checkXFO($headerArray);
//x-frame option: none
// should accept
// > passes
$headerArray = get_headers('http://wikipedia.org',1);
checkXFO($headerArray);
//x-frame option: none
// should accept
// > passes
$headerArray = get_headers('http://neopets.com',1);
checkXFO($headerArray);
//x-frame options: DENY
// should deny
// > fails
$headerArray = get_headers('http://www.yahoo.com',1);
checkXFO($headerArray);
//x-frame option:none. Redirected x-frame options: DENY
// should deny
// > fails
$headerArray = get_headers('http://www.yahoo.ca',1);
checkXFO($headerArray);
?>
关于javascript - 检测iframe src是否可显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41538675/