【发布时间】:2023-03-21 08:31:01
【问题描述】:
我有以下代码可以在 Chrome 和 MS Edge 上运行,但不能在 Firefox 上运行。
Parent.html 有这个脚本。
<html>
<body>
<script>
var ifr1 = document.createElement('iframe');
ifr1.onload = function() {
alert("iframe 1 loaded") //fires on all browsers
script = ifr1.contentWindow.document.createElement('script');
script.src = 'PATH/TO/script.js';
script.onload = function() {
alert("script 1 onload") //fires on all browsers
};
ifr1.contentWindow.document.body.appendChild(script);
};
document.body.appendChild(ifr1);
</script>
</body>
</html>
它创建一个 iframe 并在该 iframe 中加载 script.js。
这里是 script.js,它与上面做同样的事情 -
var ifr2 = document.createElement('iframe');
ifr2.onload = function() {
alert("iframe 2 loaded") //doesn't fire on Firefox
script = ifr2.contentWindow.document.createElement('script');
script.src = 'https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js';
script.onload = function() {
alert("script 2 onload")
};
ifr2.contentWindow.document.body.appendChild(script);
};
document.body.appendChild(ifr2);
它在 Parent.html 创建的 iframe ifr1 内创建另一个 iframe ifr2。
现在,Chrome 和 Edge 可以正确显示所有警报,但 Firefox 不会触发 ifr2 的 onload 事件(在 ifr1 中加载)(即使 IE 也会触发 ifr2 的 onload)。知道为什么吗?
【问题讨论】:
-
开发工具控制台上有任何消息吗?
标签: javascript html iframe