我正在编写一些 javascript 代码,并使用 window.History.pushState
加载新的 HTML
页面,而不是使用 href
标签.我的代码(工作正常)看起来像这样。
window.History.pushState({urlPath:'/page1'},"",'/page1')
奇怪的是,这失败,即重新加载浏览器
window.History.pushState({urlPath:'/page2.php'},"",'/page2.php')
但这有效,内容已更新,浏览器未刷新! (注意 URL 是绝对的而不是相对的)
window.History.pushState({urlPath:'www.domain.com/page2.php'},"",'www.domain.com/page2.php')
documentation for window.History.pushState
表示第三个参数 URL 可以是绝对的也可以是相对的 -
URL — The new history entry's URL is given by this parameter. Note that the browser won't attempt to load this URL after a call to pushState(), but it might attempt to load the URL later, for instance after the user restarts the browser. The new URL does not need to be absolute; if it's relative, it's resolved relative to the current URL. The new URL must be of the same origin as the current URL; otherwise, pushState() will throw an exception. This parameter is optional; if it isn't specified, it's set to the document's current URL.
绝对 URL 似乎有效,但相对似乎无效。为什么会这样?
最佳答案
简短的回答是history.pushState
(不是History.pushState
,会抛出异常,window
部分是可选的)永远不会按照你的建议去做。
如果页面正在刷新,那么它是由您正在执行的其他操作引起的(例如,在地址栏更改的情况下,您可能正在运行的代码转到新位置)。
history.pushState({urlPath:'/page2.php'},"",'/page2.php')
的工作方式与最新版本的 Chrome、IE 中的工作方式完全相同和 Firefox 供我和我的同事使用。
事实上,您可以在函数中添加任何您喜欢的内容:history.pushState({}, '', 'So long and Thanks for all the fish.not a real file')
。
如果您发布更多代码(特别注意 history.pushState
附近的代码以及使用 document.location
的任何地方),那么我们将不仅仅是很高兴帮助您找出这个问题的确切来源。
如果您发布更多代码,我会更新这个答案(我收藏了您的问题):)。
关于javascript - window.history.pushState 刷新浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24307401/