检测X帧选项 [英] Detect X-Frame-Options

查看:320
本文介绍了检测X帧选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法检测是否允许在iframe中加载页面?

Is there a way to detect whether or not a page is allowed to load within an iframe?

如果无法在iframe中加载网址,我希望让用户知道他们提交的网址在我们的网站上不起作用。

If a URL can not load within an iframe, I would like to let the user know that the URL they are submitting will not work on our site.

我试图获取内容,但这不起作用:

I have tried to get the contents, but that doesn't work:

$("iframe#data-url").on("load", function() {
    alert($(this).contents())
});

我不确定从哪里开始。


拒绝在 https://www.facebook.com/ 中显示因为它将'X-Frame-Options'设置为'DENY'。

Refused to display 'https://www.facebook.com/' in a frame because it set 'X-Frame-Options' to 'DENY'.

有没有办法检测 X-Frame-Options

推荐答案

因为您的脚本和目标网址位于不同的域中,JavaScript的跨域策略不允许您访问标头。几个月前我遇到了同样的问题,最后使用JavaScript向一个PHP文件发送一个AJAX请求,然后可以解析标题。

Because your script and the target URL are on different domains, JavaScript's cross domain policy won't let you access the headers. I ran into the same problem a few months ago and ended up using JavaScript to send an AJAX request to a PHP file which could then parse the headers.

这就是我的意思有PHP文件。然后,这将返回JSON数组中的结果。让我知道它是否有帮助!

This is what I had in the PHP file. This would then return the result in a JSON array. Let me know if it helps!

$error=false;
$urlhere='http://facebook.com';
$ch = curl_init();

$options = array(
        CURLOPT_URL            => $urlhere,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HEADER         => true,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_ENCODING       => "",
        CURLOPT_AUTOREFERER    => true,
        CURLOPT_CONNECTTIMEOUT => 120,
        CURLOPT_TIMEOUT        => 120,
        CURLOPT_MAXREDIRS      => 10,
);
curl_setopt_array($ch, $options);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch);
$headers=substr($response, 0, $httpCode['header_size']);
if(strpos($headers, 'X-Frame-Options: deny')>-1||strpos($headers, 'X-Frame-Options: SAMEORIGIN')>-1) {
        $error=true;
}
$httpcode= curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
echo json_encode(array('httpcode'=>$httpcode, 'error'=>$error));

我知道这不是一个理想的回应,但我可以完成我的项目。

I know it's not an ideal response but it's all I could get to work with my project.

编辑 Bill ,如果您更改 strpos() stripos() 您可能会获得更好的结果,因为它会运行不区分大小写的搜索。

As Bill stated below, if you change strpos() to stripos() you might get better results as it runs a case insensitive search instead.

这篇关于检测X帧选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆