我正在编写一个 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 .它声称他们拥有可以检测顶级窗口 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."
那么,有没有办法检测顶级窗口 url?
类似问题: Top window's URL form inside of multiple nested cross-domain iFrames
最佳答案
如果您在同一域中,则可以使用
访问顶部框架window.top.location.href
这是简单的答案。
如果您的嵌套 iframe 位于与您的顶级域不同的域中,那么您将遇到同源策略问题,即出于安全原因托管在不同域中的框架无法相互通信。
如果您控制嵌套框架的创建,一种解决方法是传递一个指向您的嵌套框架的查询字符串参数。
另一种方法是使用 HTML5 postMessage 在框架之间进行通信,但同样,这需要您对两个域都具有控制权。
希望对您有所帮助。
关于javascript - 从多级跨域 iframe 确定顶级窗口的 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27728570/