History replaceState不再在Chrome中为本地文件工作

8tntrjer  于 12个月前  发布在  Go
关注(0)|答案(3)|浏览(102)

我正在使用window.history.replaceState()来更改一个HTML文件的查询字符串,该文件是使用file:/C:/...
这曾经在Chrome,Internet Explorer和Firefox中工作,但不再在Chrome中工作。不知道什么时候停止工作。Chrome 45.0.2454.85它仍然适用于其他2个浏览器。
我得到:
未捕获的安全性错误:无法对“历史记录”执行“replaceState”:URL为“file:/C:/Users/Michael/Desktop/test.html”的历史记录状态对象?无法在原始为“null”的文档中创建“Q=NewQueryString”。
对不起,但这在任何托管的fiddle中都不起作用。您可以将代码复制到本地HTML文件中,以便自己查看:

<html>
<body>
<button onclick="clickme()">Click me</button>
<script>
function clickme() {
    window.history.replaceState({ "html": undefined, "pageTitle": "NewTitle"}, "", "?Q=NewQueryString");
}
</script>
</body>
</html>

显然,我可以在服务器上托管这个,但试图保持简单。这是一个简单的scrum板,我们正在使用Git托管。它会访问第三方Web服务来获取数据。任何关于解决错误的想法。

gg58donl

gg58donl1#

它在Chrome 45上停止工作。在这里,我填写了一个问题code.google:https://code.google.com/p/chromium/issues/detail?id=529313
如果您只需要在自己的计算机上运行它,那么设置--allow-file-access-from-files是一个很好的解决方案。

hxzsmxv2

hxzsmxv22#

我也有同样的问题。作为一种变通方法,我在启动Chrome时使用了--allow-file-access-from-files标志。
但认为这不是最好的解决办法。
下面是我如何运行的示例:
“C:\Program Files(x86)\Google\Chrome\Application\chrome.exe”--app=file:/C:/APP/index.html--allow-file-access-from-files
如果有人找到更好的解决方案,请让我们知道。

ztmd8pv5

ztmd8pv53#

Chromium团队将其标记为WontFix,并建议不要在应用程序中使用file:// URL。
你有两个选择:

选项A:使用hash代替。

您仍然可以使用window.history.replaceState/pushState修改file:// URL的hash组件。
要设置一些哈希参数:

window.history.replaceState(null, "", "#?a=param1&b=param2);

读取一些哈希参数:

const hashString = window.location.hash;
const queryString = hashString.startsWith("#?") ? hashString.substring(2) : hashString;
const queryParams = new URLSearchParams(queryString);

要清除哈希参数,请执行以下操作:

// Clear query string
window.history.replaceState(null, "", window.location.pathname + window.location.search);

选项B:使用document.location.href作为传统行为

可以将document.location.href更新为这些文件URL的黑客解决方案。这将重新加载页面,但根据应用程序,这可能仍然可行。
如果不是file:// URL,您仍然可以继续使用典型的window.history.replaceState/pushState功能。
举例来说:

const queryString = "a=param1&b=param2"

// Set query string
if (window.location.protocol === "file:") {
  // If application is opened as a file (not served over HTTP), we cannot use `window.history`.
  const newLocation = `${window.location.protocol}//${window.location.pathname}?${queryString}`;
  if (document.location.href !== newLocation) {
    document.location.href = newLocation;
  }
} else {
  window.history.replaceState(null, "", `/?${queryString}`);
}

相关问题