原文地址: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.(结尾这句没看懂,不看了。。。)