从多级跨域 iframe 中确定顶级 window 的 url

Determine url of top level window from a multilevel cross domain iframe

我正在编写一个 JavaScript 像素,它将与发布商页面上的广告创意一起投放。此 AD 将包含在发布商网站上的跨域 iframe(有时是多个级别)中。所以发布者页面看起来像这样

主机(发布商)站点

<html>
    <iframe src="http://domain1.com" name="first_level_iframe">
        <iframe src="http://domain2.com" name="second_level_iframe">
            <!--The script I want to write will be hosted here-->
        </iframe>
    </iframe>
</html>

如果广告商想知道他/她的广告在哪些页面上投放,那么我们需要知道主机页面 url。

如前所述here我们可以像这样使用document.referrer得到父页面url

var url = (window.location != window.parent.location) ? document.referrer: document.location;

但它仅适用于仅上一级的域。我们无法到达最顶层,因为我们对“domain1.com”iframe 没有任何控制权。 这是人们长期以来一直试图解决的一个问题,SO 上已经有很多问题完全相同。 但是因为这个article,我又来问了。它声称他们有一个专利解决方案,可以检测顶级 window url。这是博客的摘录

The lifesaver was a technique developed at AdSafe: The key to the solution was the ability to read the address of the top frame that was hosting the ad(*). We were detecting porn because the ads that were supposed to appear within a "clean publisher" site were appearing within the frame of a porn website. Think of HGTV as an illustrative, but not the real, example of such a "clean publisher."

那么,有没有办法检测到顶级window url?

类似问题: Top window's URL form inside of multiple nested cross-domain iFrames

如果您在同一域中,则可以使用

访问顶部框架
window.top.location.href

答案很简单。

如果您的嵌套 iframe 位于与您的顶级域不同的域中,那么您将 运行 陷入同源策略问题,即出于安全原因,托管在不同域中的框架无法相互通信.

如果您控制嵌套框架的创建,一种解决方法是传递一个指向嵌套框架的查询字符串参数。

另一种方法是使用 HTML5 postMesssage 在框架之间进行通信,但同样,这需要您对两个域都具有控制权。

希望对您有所帮助。

我有一个解决方案可以让你在 Chrome 和 Opera 中获取域(在多个嵌套的 cross-domain iframe 中),但不幸的是,它在其他浏览器中是不可能的。

您可以使用 'window.location.ancestorOrigins' 属性.

这段代码将跨浏览器运行,为您获取最接近的页面 URL:https://gist.github.com/ocundale/281f98a36a05c183ff3f.js