从两级深度 iframe 获取浏览器 URL

Get browser URL from two level depth iframe

本文关键字:iframe 获取 浏览器 URL 深度 两级      更新时间:2023-09-26

在另一个iframe中有一个iframe。我想从第二个iframe获取浏览器的 URL(例如:http://test)。

//browser URL: http://test <-- I need this URL
<iframe src="http://level1">
    <iframe src="http://level2">
        <!-- some content -->
    </iframe>
</iframe>

我尝试了document.referrer但它返回了第一个 iframe 的 URL:

<iframe src="http://level1">
    <iframe src="http://level2">
        console.log(document.referrer); //It gives back http://level1
    </iframe>
</iframe>

更新:

top.location.href不起作用,因为存在不同的域。不同的浏览器,第一个和第二个 iframe 域。(我们的网站 - 广告服务器 - 第三方网站)

如前所述,跨域 iframe 通常是不可能的,但在 Chrome 的情况下,您可以使用window.location.ancestorOrigins,如果您位于多个 iframe 中,它将为您提供"顶级网址"和所有域的列表,无论它们是否跨域。