Edge 中 iframe 中的几个 document.write 导致 SCRIPT70: Permission denied

Several document.write in iframe in Edge cause SCRIPT70: Permission denied

document.write 导致错误 SCRIPT70:如果您在 iframe 中使用一些 document.write,则权限被拒绝。此错误仅发生在 Edge 中。在所有其他浏览器中,不会观察到此错误。 例如:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SSP-558</title>
</head>
<body>
<script>
    document.write("1");
    document.write("2");
</script>
<script>
    var iframe = document.createElement("iframe");
    iframe.width = window.outerWidth;
    iframe.height = window.outerHeight;
    iframe.onload = function () {
        var doc = iframe.contentWindow.document;
        var script = doc.createElement("script");
        script.type = "text/javascript";
        script.text = [
            'document.write("1");',
            'document.write("2");'
        ].join("");

        doc.body.appendChild(script);
    };
    document.body.appendChild(iframe);
</script>
</body>
</html>

这段代码会在页面和iframe中显示12,但会导致错误,在Edge中iframe中只显示1。

如果你只使用一个 document.write 一切正常。不幸的是,包含多个 document.write 的代码来自第三方开发人员,他们无法更改它。

您遇到过这个错误吗?有什么解决办法吗?

已找到解决方案。如果在document.write前面加上window就不会报错

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>SSP-558</title>
</head>
<body>
<script>
    document.write("1");
    document.write("2");
</script>
<script>
    var iframe = document.createElement("iframe");
    iframe.width = window.outerWidth;
    iframe.height = window.outerHeight;
    iframe.onload = function () {
        var doc = iframe.contentWindow.document;
        var script = doc.createElement("script");
        script.type = "text/javascript";
        script.text = [
            'window.document.write("1");',
            'window.document.write("2");'
        ].join("");

        doc.body.appendChild(script);
    };
    document.body.appendChild(iframe);
</script>
</body>
</html>