小编典典

JavaScript SecurityError:阻止了具有原始位置的框架访问跨域框架

javascript

我正在<iframe>HTML页面中加载,并尝试使用Javascript访问其中的元素,但是当我尝试执行代码时,出现以下错误:

SecurityError: Blocked a frame with origin "http://www.<domain>.com" from accessing a cross-origin frame.

您能否帮助我找到解决方案,以便我可以访问框架中的元素?

我正在使用此代码进行测试,但徒劳无功:

$(document).ready(function() {
    var iframeWindow = document.getElementById("my-iframe-id").contentWindow;

    iframeWindow.addEventListener("load", function() {
        var doc = iframe.contentDocument || iframe.contentWindow.document;
        var target = doc.getElementById("my-target-id");

        target.innerHTML = "Found it!";
    });
});

阅读 549

收藏
2020-04-22

共1个答案

小编典典

同源政策

您无法<iframe>使用JavaScript访问其他来源的内容,如果可以的话,这将是一个巨大的安全漏洞。对于同源策略,浏览器会阻止脚本尝试访问来源不同的框架。

如果未保留地址的以下至少之一,则认为起源是不同的:

<protocol>://<hostname>:<port>/...

*如果要访问框架, *协议主机名端口 必须与您的域相同。

注意:众所周知InternetExplorer并不严格遵循此规则。

例子

尝试从中访问以下URL会发生以下情况 http://www.example.com/home/index.html

URL                                             RESULT 
http://www.example.com/home/other.html       -> Success 
http://www.example.com/dir/inner/another.php -> Success 
http://www.example.com:80                    -> Success (default port for HTTP) 
http://www.example.com:2251                  -> Failure: different port 
http://data.example.com/dir/other.html       -> Failure: different hostname 
https://www.example.com/home/index.html:80   -> Failure: different protocol
ftp://www.example.com:21                     -> Failure: different protocol & port 
https://google.com/search?q=james+bond       -> Failure: different protocol, port & hostname

解决方法

即使同源策略阻止脚本访问源不同的站点的内容,但是
如果您同时拥有两个页面,则可以使用window.postMessage及其相对message事件在两个页面之间发送消息来 解决此问题
,如下所示:

  • 在您的主页中:
    let frame = document.getElementById('your-frame-id');
    

    frame.contentWindow.postMessage(/any variable or object here/, 'http://your-second-site.com’);

的第二个参数postMessage()可以是'*'指示对目的地的起点没有任何偏好。在可能的情况下,应始终提供目标来源,以避免泄露您发送到任何其他站点的数据。

  • 在您的<iframe>(包含在主页中):
    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; 
    }
    

    });

此方法可以在 两个方向
上应用,也可以在主页上创建侦听器,并从框架接收响应。相同的逻辑也可以在弹出窗口中实现,并且基本上也可以在主页中(例如使用window.open())生成的任何新窗口中实现,没有任何区别。

在禁用同源策略 您的 浏览器

关于该主题已经有了一些很好的答案(我刚刚找到了它们),因此,对于可能的浏览器,我将链接相对答案。但是,请记住, 禁用同源策略只会影响 您的
浏览器
。此外,运行禁用了同源安全设置的浏览器会授予 任何 网站访问跨域资源的权限,因此,
这是非常不安全的,如果您不确切知道自己在做什么(例如,出于开发目的),则永远不要这样做

  • Google Chrome
  • Mozilla Firefox
  • Safari
  • Opera
  • Microsoft Edge: not possible
  • Microsoft Internet Explorer
2020-04-22