Edge 和 IE:创建 iframe 并访问窗口对象后权限被拒绝



在脚本中创建iframe时,我在Edge和IE上收到"权限被拒绝"错误,并有一些延迟(setTimeout)并尝试访问窗口对象。

它适用于所有其他浏览器,并且在IE和Edge上没有延迟。

<script>
function createIframe(win) {
console.log('foo', win.foo);
var width = 300;
var height = 250;
var id = 'ifr';
var src = '';
var iframeTemplate = '<iframe id="'+id+'" src="'+src+'" width="'+width+'" height="'+
height+'"  marginheight="0" marginwidth="0" scrolling="NO" frameborder="0"></iframe>';
win.document.write(iframeTemplate);
var iframe = win.document.getElementById(id);
console.log('foo', win.foo);
if (iframe) {
var doc = iframe.contentWindow.document;
doc.write('<html><head></head><body><script>console.log("foo on parent", window.parent.foo);</scr'+ 'ipt></body></html>');
doc.close();
} else {
console.log('Failed to create an iframe');
}
}
window.foo = 'bar';
setTimeout(function() {
createIframe(window);
}, 3000);
</script>

此代码应打印:

foo bar
foo bar
foo on parent bar

但它在第二个控制台上抛出错误"权限被拒绝".log在 Edge 和 IE 上。

无需设置超时即可正常工作。

如果我从 iframe 中删除第二个控制台.log和 accessss window.parent.foo,它在 Edge 和 IE 上是未定义的

片段:

在Edge 和 IE 上不起作用:https://jsfiddle.net/vo2yrjft/

适用于边缘和IE:https://jsfiddle.net/6cbfk1yr/

有什么解决方法吗?

document.write

是一种"不好的做法",它会阻止页面,您可以参考此线程以获取详细信息。

作为一种解决方法,您可以使用createElement('iframe')创建 iframe,然后使用appendChild()插入元素。下面是示例代码,它可以在IE&Edge中运行良好:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<script>
function prepareFrame(win) {
console.log('foo', win.foo);
var id = 'ifr';
var ifrm = document.createElement('iframe');
ifrm.setAttribute('src', '');
ifrm.setAttribute('id', id);
ifrm.setAttribute('marginheight', 0);
ifrm.setAttribute('marginwidth', 0);
ifrm.setAttribute('scrolling', 'NO');
ifrm.setAttribute('frameborder', 0);
ifrm.style.width = '300px';
ifrm.style.height = '250px';
document.body.appendChild(ifrm);
var iframe = win.document.getElementById(id);
console.log('foo', win.foo);
if (iframe) {
var doc = iframe.contentWindow.document;
doc.write('<html><head></head><body><script>console.log("foo on parent", window.parent.foo);</scr' + 'ipt></body></html>');
doc.close();
} else {
console.log('Failed to create an iframe');
}
}
window.foo = 'bar';
setTimeout(function() {
prepareFrame(window);
}, 3000);
</script>
</body>
</html>

最新更新