当来源不同时从iframe获取网址

问题描述 投票:3回答:3

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

例如:

<iframe src="startingUrl" class="embed-responsive-item" id="iframe" sandbox="" allowfullscreen</iframe>

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

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

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

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

iFrame中的网站不是我的。

非常感谢所有帮助!

javascript html iframe same-origin-policy
3个回答
1
投票

简短回答:这是不可行的,除非您在iframe中获得其他网站的支持,并且他们愿意在@박상수回答中添加代码。

更长的答案:您可以设置代理服务器以注入所需的代码来完成这项工作,但是您会遇到法律和道德上的困难,因此,我将不深入解释如何做到这一点。 。

另一种方法可能是创建一个浏览器扩展并让您的用户安装它。我要再次指出,FaceBook过去采用这种方法遇到了道德上的困难。

最终,这是出于很好的安全原因,浏览器会阻止您执行此操作,并且您应该尊重这些原因而不应该这样做。


0
投票

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

console.log(iframe.src);

查看此链接

SecurityError: Blocked a frame with origin from accessing a cross-origin frame

let frame = document.getElementById('your-frame-id');
frame.contentWindow.postMessage(/*any variable or object here*/, 'http://your-second-site.com');
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; 
    } 
}); 

0
投票

您将要覆盖自动引发的错误:

const iframe = document.getElementById('iframe');
iframe.addEventListener('load', evt => {
  const loc = iframe.contentWindow.location;
  try{
    loc.href;
  }
  catch(e){
    if(e.name === 'SecurityError'){
      console.log(iframe.src);
    }
  }
});
<iframe src='https://example.com' class='embed-responsive-item' id='iframe' sandbox='' allowfullscreen></iframe>
© www.soinside.com 2019 - 2024. All rights reserved.