首页 > 解决方案 > 历史 API 空状态

问题描述

在使用 Ajax 更改我的 DOM 后,我也尝试更改 URL(不刷新页面)。

$("nav li").click(function(e) {
    e.preventDefault();
    var url;
    var targetLocation = this.parentNode.attributes.href.value;
    switch (targetLocation) {
    case "index.html": url = "http://localhost:8080/home"; break;
    case "app.html": url = "http://localhost:8080/api"; break;
    case "contact.html": url = "http://localhost:8080/contact"; break;
    }

    $.ajax({
        type: "GET",
        dataType: "text",
        url: url,
        context: document.body,
        success: function(data) {
            $("div").text(data);
            history.pushState("", "", targetLocation);
        }
    })
})

但我收到一条错误消息:

Uncaught DOMException: failed to execute "pushState" on "History": A history state object with URL "file:///C:/test/app.html" cannot be created in a document with origin "null" and URL "file:///C:/test/index.html".

标签: javascriptjqueryajaxhtml5-history

解决方案


您的代码不包含它们,但您的错误表明您正在使用本地文件。浏览器不支持对本地文件系统 URL 的历史操作。

file:// URL 的安全模型已损坏,无法修复。我们没有通过 file:// URL 的特殊情况使浏览器复杂化,而是选择通过使一类安全检查失败来禁用 file:// URL 的某些功能。不幸的是,pushState 就是这些特性之一。我建议不要在您的应用程序中使用 file:// URL。

https://bugs.chromium.org/p/chromium/issues/detail?id=301210

找不到 Firefox 的参考,但 IIRC 他们的行为与 Chrome 的相同。


推荐阅读