【问题标题】:Calling history.pushState() inside a new document created by document.write() causes SecurityError on Internet Explorer 11在由 document.write() 创建的新文档中调用 history.pushState() 会导致 Internet Explorer 11 上出现 SecurityError
【发布时间】:2019-03-13 09:52:05
【问题描述】:

获取以下代码,通过网络服务器提供它,例如http-server(节点包)。我有一个示例服务器 here

<meta http-equiv="Cache-Control" content="max-age=0"/>
<script>
window.onload = function() {
    document.write('<script>history.pushState(null, null, "bar.html");console.log("passed");\u003c/script>');
}
</script>

请注意,Cache-Control 标头存在是因为 IE 出于某种原因主动缓存了该页面。这在我的测试过程中对我有帮助,但不是重现问题所必需的。

当我在 IE11 (Windows 10) 中加载页面时,我在控制台上打印了一个 SecurityError,没有 URL 更改,也没有打印“通过”。

在 Edge 16 中,我将“通过”打印到控制台,但 URL 没有更改。

在 Firefox 和 Chrome 中,这可以正常工作:URL 发生变化,我得到“通过”打印到控制台。

为什么 IE 会出现这种行为,我如何将 document.write()pushState() 结合使用?我的意图是覆盖整个文档,而不是简单地附加到它(这就是我使用window.onload 的原因)。

【问题讨论】:

    标签: javascript html internet-explorer internet-explorer-11


    【解决方案1】:

    尝试在代码中添加 Try...Catch,然后尝试使用 IE11 进行测试。

    <html>
    <body>
    <script>
    try {
    history.pushState(null, null,"bar.html");
    console.log("passed");
    }
    catch(err) {
        document.getElementById("demo").innerHTML = err.message;
    }
    </script>
    </body>
    </html>

    输出:

    【讨论】:

    • 这个答案不使用document.write()window.onload 如我的问题所述。
    【解决方案2】:

    如果有人遇到过同样的问题,可以在 IE11 中解决此问题。

    只需执行location.href = location.href + '#fix-ie' 即可更改 URL 而无需重新加载页面。这必须在一开始就完成,在其他任何事情都有机会执行 history.pushStatehistory.replaceState 之前。

    这似乎将location.href“移动”到新文档中。

    完整代码:

    let original = location.href;
    if (original.indexOf('#') === -1) {
        location.href = original + '#ie-fix';
        location.href = original + '#';
    } else {
        location.href = original + 'ie-fix';
        location.href = original;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-01-20
      • 1970-01-01
      • 1970-01-01
      • 2016-01-09
      • 2015-07-10
      • 1970-01-01
      • 1970-01-01
      • 2022-01-01
      • 2023-03-02
      相关资源
      最近更新 更多