如果 iframe 的内容是不同的域,那么您对它执行的 JavaScript 数量将非常有限。你可以在这里https://www.cakemail.com/blog/the-iframe-cross-domain-policy-problem/了解更多关于为什么在这篇文章中。
我个人发现使用postMessage API 是一种有用的解决方法,因为它适用于正确的用例(例如,您必须能够让 iframe 内容提供商托管的代码来处理消息)。这往往适合我的工作用例与其他软件公司的合作伙伴集成。
您可以在此处找到此方法的示例:
https://codepen.io/wickdninja/pen/oygwNL?editors=1111
// parent js
console.log('1 - parent');
var iframe = document.getElementById('iframe');
iframe.addEventListener("load", function(event){
console.log('3 - parent on iframe load');
iframe.contentWindow.postMessage('testing','*')
}, false);
iframe.contentWindow.addEventListener('message', function(event){
console.log('recieved message event from child')
console.log(event.data);
});
// parent html
<h1>Parent Frame</h1>
<iframe id="iframe" src="https://s.codepen.io/wickdninja/debug/GGgEKE/DqkDdKzORQXk"></iframe>
// child js
console.log('2 - child');
window.addEventListener('message', function(event){
console.log('4 - on child message')
console.log('child postMessage with * origin')
}, false);
window.parent.postMessage('test from child', '*')
// child html
<h1>Child Frame</h1>
// console output from parent
"1 - parent"
"3 - parent on iframe load"
"recieved message event from child"
"testing"