Preventing IFRAME embedding, but with one exceptio

2019-08-03 00:22发布

问题:

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);
}

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.

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?

Is this OK?

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

回答1:

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.

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.

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.



回答2:

If you pass X-FRAME-OPTIONS http header with the value of SAMEORIGIN, most modern browsers (including IE8) will not let the content be iframed from an alien domain.

I thought it may help.