同源策略
You can't访问一个<iframe>
使用 JavaScript 的不同来源,如果你能做到这一点,那将是一个巨大的安全漏洞。为了同源策略 https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy 浏览器阻止脚本尝试访问具有不同来源的框架.
如果地址的以下部分至少之一未维护,则认为来源不同:
protocol://hostname:port/...
如果您想访问框架,协议、主机名和端口必须与您的域相同。
NOTE: though mostly unused nowadays, Internet Explorer is known to not strictly follow this rule, see here https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy#Exceptions_in_Internet_Explorer for details.
Examples
以下是尝试访问以下 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 https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage及其亲戚message
event在两个页面之间发送消息,如下所示:
-
在您的主页中:
const frame = document.getElementById('your-frame-id');
frame.contentWindow.postMessage(/*any variable or object here*/, 'https://your-second-site.example');
第二个参数postMessage()
can be '*'
表明对目的地的出发地没有偏好。应尽可能提供目标来源,以避免泄露您发送到任何其他站点的数据。
-
In your <iframe>
(包含在主页中):
window.addEventListener('message', event => {
// IMPORTANT: check the origin of the data!
if (event.origin === 'https://your-first-site.example') {
// 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() https://developer.mozilla.org/en-US/docs/Web/API/Window/open)同样如此,没有任何区别。
禁用同源策略your browser
关于这个主题已经有一些很好的答案(我刚刚在谷歌上找到了它们),因此,对于可能的浏览器,我将链接相关答案。但是,请记住禁用同源策略只会影响your browser。此外,运行具有同源安全设置的浏览器禁用授权any网站访问跨域资源,所以这是非常不安全的,如果您不确切知道自己在做什么(例如开发目的),则永远不要这样做.
- 谷歌浏览器 https://stackoverflow.com/q/3102819/3889449
- 火狐浏览器 https://stackoverflow.com/q/17088609/3889449
- Safari https://stackoverflow.com/q/4556429/3889449
-
Opera https://stackoverflow.com/q/7543678/3889449:与 Chrome 相同
- Microsoft Edge:与 Chrome 相同
- Brave:与 Chrome 相同
- Microsoft Edge(旧的非 Chromium 版本):不可能 https://superuser.com/q/1020612/591004
- 微软浏览器 https://stackoverflow.com/q/20947359/3889449