我正在写一个基于iframe的facebook应用程序。现在我想使用相同的html页面来渲染正常的网站以及facebook内的画布页面。我想知道我是否可以确定页面是否已经在iframe内加载或直接在浏览器中加载?
当前回答
使用这个javascript函数作为如何实现这一点的例子。
function isNoIframeOrIframeInMyHost() {
// Validation: it must be loaded as the top page, or if it is loaded in an iframe
// then it must be embedded in my own domain.
// Info: IF top.location.href is not accessible THEN it is embedded in an iframe
// and the domains are different.
var myresult = true;
try {
var tophref = top.location.href;
var tophostname = top.location.hostname.toString();
var myhref = location.href;
if (tophref === myhref) {
myresult = true;
} else if (tophostname !== "www.yourdomain.com") {
myresult = false;
}
} catch (error) {
// error is a permission error that top.location.href is not accessible
// (which means parent domain <> iframe domain)!
myresult = false;
}
return myresult;
}
其他回答
我用这个:
var isIframe = (self.frameElement && (self.frameElement+"").indexOf("HTMLIFrameElement") > -1);
这对我来说是最简单的解决方案。
<p id="demofsdfsdfs"></p>
<script>
if(window.self !== window.top) {
//run this code if in an iframe
document.getElementById("demofsdfsdfs").innerHTML = "in frame";
}else{
//run code if not in an iframe
document.getElementById("demofsdfsdfs").innerHTML = "no frame";
}
</script>
目前最好的遗留浏览器断帧脚本
其他的解决方法对我都不起作用。这条适用于所有浏览器:
防止点击劫持的一种方法是在每个不应该被框起来的页面中包含一个“打破框架”脚本。下面的方法将防止网页被框架,即使在传统浏览器,不支持X-Frame-Options-Header。
在文档HEAD元素中,添加以下内容:
<style id="antiClickjack">body{display:none !important;}</style>
首先对style元素本身应用一个ID:
<script type="text/javascript">
if (self === top) {
var antiClickjack = document.getElementById("antiClickjack");
antiClickjack.parentNode.removeChild(antiClickjack);
} else {
top.location = self.location;
}
</script>
这样,所有内容都可以在文档HEAD中,并且在API中只需要一个方法/taglib。
参考:https://www.codemagi.com/blog/post/194
在Firefox 6.0扩展(Addon-SDK 1.0)的内容脚本中,接受的答案对我来说不起作用:Firefox在每个:顶级窗口和所有iframe中执行内容脚本。
在内容脚本中,我得到以下结果:
(window !== window.top) : false
(window.self !== window.top) : true
这个输出的奇怪之处在于,无论代码是在iframe中运行还是在顶级窗口中运行,它总是相同的。
另一方面,谷歌Chrome似乎只在顶级窗口内执行我的内容脚本一次,所以上面不会工作。
在两种浏览器的内容脚本中,最终为我工作的是:
console.log(window.frames.length + ':' + parent.frames.length);
如果没有iframe,则打印0:0,在包含一个框架的顶级窗口中打印1:1,在文档的唯一iframe中打印0:1。
这允许我的扩展在两个浏览器中确定是否存在任何iframes,此外,在Firefox中,如果它是在iframes之一中运行。
浏览器会阻塞对窗口的访问。顶部由于同源政策。IE漏洞也会发生。下面是工作代码:
function inIframe () {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
}
Top和self都是窗口对象(还有父窗口),所以你会看到你的窗口是否是顶部窗口。