防止IFRAME嵌入,但有一个例外 [英] Preventing IFRAME embedding, but with one exception

查看:116
本文介绍了防止IFRAME嵌入,但有一个例外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们在给定位置有一个网页(例如 www.foo.com/page1.html ),该页面包含此(全局)代码:

Let's say we have a web-page at a given location (like www.foo.com/page1.html) and that page contains this (global) code:

if (self != top) {
    top.location.replace(location.href);
}

因此,如果我们尝试将该页面加载到IFRAME中,页面将会跳出iframe进入浏览器窗口,这将(因此)销毁包含iframe的页面。

So, if we try to load that page into an IFRAME, the page will "jump" out of the iframe into the browser window, which will (as a consequence) destroy the page that contained the iframe.

这没关系,但我想实现该规则的例外。具体来说,在另一个域上有这个其他页面(比如 www.bar.com/page2.html ),我希望其他页面能够通过IFRAME嵌入第一页。

This is OK, but I would like to implement an exception to that rule. Specifically, there is this other page on a different domain (like www.bar.com/page2.html), and I would like that this other page is able to embed the first page via an IFRAME.

我如何修改第一页的代码,以便它可以嵌入到另一页?

How would I have to modify the code of the first page, so that it allows to be embedded into the other page?

这可以吗?

if (self != top && top.location.href !== "http://www.bar.com/page2.html") {
    top.location.replace(location.href);
}


推荐答案

我怀疑你会不会能够检查外部父页面的URL,因为同源策略应该阻止访问其任何属性。

I doubt you'll be able to check the external parent page's URL because the Same Origin Policy should prevent access to any of its properties.

也许有一些我知道的诡计无论如何都允许它。除此之外,我想到的最好的想法是检查 document.referrer 。据我所知,在 iframe 中请求的文档将始终在浏览器的引荐来源中包含嵌入页面的URL。

Maybe there is some trickery that I'm aware of that allows it anyway. Barring that, the best idea that comes to my mind is checking document.referrer. As far as I know, a document requested in an iframe will always have the embedding page's URL in the referrer across browsers.

如果推荐人是 http://www.bar.com/page2.html ,该页面要么是在该页面上的iframe中,或者它是从那里链接的(这是该方法唯一真正的大缺点:你不能100%确定它是传入链接还是iframe嵌入)。

If the referrer is http://www.bar.com/page2.html, the page is either in an iframe on that page, or it was linked to from there (which is the only really big shortcoming of this method: You can't tell for 100% sure whether it's an incoming link, or an iframe embed).

显然,客户可以欺骗该文件的推荐人,但我不认为这是一个问题。

Obviously, the document's referrer is spoofable by the client but I don't think that's an issue here.

这篇关于防止IFRAME嵌入,但有一个例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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