Same-origin security policy

原文地址http://stackoverflow.com/questions/25098021/securityerror-blocked-a-frame-with-origin-from-accessing-a-cross-origin-frame

翻译如下

问题:

从页面的<iframe>中使用JavaScript 获取内容到本地,出现跨域请求错误的问题,浏览器的安全性机制不允许我这样做,怎么办?

原文错误:

SecurityError: Blocked a frame with origin "http://www.<domain>.com" from accessing a cross-origin frame.
解决方法:
浏览器的安全机制就是不允许用JavaScript获取iframe中的内容,在同一个域中才可以获取

<<strong>protocol</strong>>://<<strong>hostname</strong>>:<<strong>port</strong>>/path/to/page.html
protocol、hostname 和 port 都必须完全相同

举例如下:

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.html -> Failure: different protocol
ftp://www.example.com:21                     -> Failure: different protocol & port
https://google.com/search?q=james+bond       -> Failure: different hostname & protocol
解决办法

在自己的页面中使用 window.postMessage和它对应的message 事件。

在你的主页面

var frame = document.getElementById('your-frame-id');

frame.contentWindow.postMessage(/*any variable or object here*/, '*');

在你的 <iframe>中(包含在主页面)

window.addEventListener('message', function(event) {

    // IMPORTANT: Check the origin of the data!
    if (~event.origin.indexOf('http://yoursite.com')) {
        // The data has been sent from your site

        // The data sent with postMessage is stored in event.data
        console.log(event.data);
    } else {
        // The data hasn't been sent from your site!
        // Be careful! Do not use it.
        return;
    }
});

这种方法是双向的,也可以在主页面监听,接收从frame中获得的内容。


The same logic can also be implemented in pop-ups and basically any new window generated by the main page (e.g. using window.open()) as well, without any difference.(结尾这句没看懂,不看了。。。)








 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值