当原点不同时从 iframe 获取 url

Lau*_*ont 5 html javascript iframe same-origin-policy

当用户通过单击 iframe 中的链接重定向时,我想从 iframe 获取 URL。iframe 的来源与 Web 应用程序不同。

例如:

<iframe src="startingUrl" class="embed-responsive-item" id="iframe" sandbox="" allowfullscreen</iframe>
Run Code Online (Sandbox Code Playgroud)

我在 iframe 上添加了一个加载侦听器,以检测用户何时重定向到此 iframe 中的其他 url:

const iframe = document.getElementById("iframe");

iframe.addEventListener("load", (evt) => {
    const location = iframe.contentWindow.location;

    console.log(location); // this gives me a Location object where I can see the href property
    console.log(location.href); // this gives me a SecurityError: Permission denied to get property "href" on cross-origin object, I also tried to get a copy of the object but that doesn't work either.
});
Run Code Online (Sandbox Code Playgroud)

我知道是什么导致了这个问题,我也知道这是不可能的。但是我需要找到一种方法来获取页面的当前 URL。如果这是不行的,那么我希望使用此 Web 应用程序的用户可以复制 iframe 的 url 并将其放入输入字段。

现在,他们可以在 chrome 中执行“查看框架源”和此框架:在 Firefox 中查看框架源或信息。但这对用户来说太复杂了。有没有办法让他们看到 iFrame 中的 URL,或者让用户更简单地获取 URL。

iFrame 中的站点不是我的。

非常感谢所有帮助!

小智 0

如果您没有看到下面的代码,请检查下面的链接。

console.log(iframe.src);
Run Code Online (Sandbox Code Playgroud)

查看此链接

SecurityError:阻止具有来源的框架访问跨来源框架

let frame = document.getElementById('your-frame-id');
frame.contentWindow.postMessage(/*any variable or object here*/, 'http://your-second-site.com');
Run Code Online (Sandbox Code Playgroud)
window.addEventListener('message', event => {
    // IMPORTANT: check the origin of the data! 
    if (event.origin.startsWith('http://your-first-site.com')) { 
        // The data was sent from your site.
        // Data sent with postMessage is stored in event.data:
        console.log(event.data); 
    } else {
        // The data was NOT sent from your site! 
        // Be careful! Do not use it. This else branch is
        // here just for clarity, you usually shouldn't need it.
        return; 
    } 
}); 
Run Code Online (Sandbox Code Playgroud)