我在我的 ajax 应用程序中使用 pushStates 从一个“页面”导航到另一个“页面”。现在,我想看看我来自哪个页面。但是 document.referrer
总是返回 ""
。或者,当我从另一个页面(链接所在的页面)打开我的应用程序时,我从另一个页面获得了 URL。
这些行不应该...
history.pushState({}, "Some title", "/some/valid/url/1");
history.pushState({}, "Some title", "/some/valid/url/2");
...产生这样的推荐人:
http://somedomain.com/some/valid/url/1
?
或者换句话说:有没有办法相应地设置 document.referrer
,或者至少将其重置为 ""
?
注意:我正在寻找不在某个变量中缓存以前的 URL 的解决方案。我需要真正改变 document.referrer
的东西,因为我无法改变依赖它的脚本。
最佳答案
简答:使用 window.location
而不是 history.pushState
更长的答案:
document.referrer
根据 MDN : “如果用户直接导航到页面(不是通过链接,而是例如通过书签),则该值为空字符串”
直接操作history
状态不会被视为跟随链接。您可以通过更新 window.location
( MDN ) 来模拟链接点击,这也会自动更新历史记录。
例如,使用 https://github.com/kanaka/mal/
加载一个选项卡。然后一次键入以下一行(否则它们都在单个 javascript 执行上下文中运行,并且只应用最后的位置更新)
console.log(history.length) // 2
console.log(document.referrer) // ""
window.location = "/kanaka/mal/tree/master/ada"
console.log(history.length) // 3
console.log(document.referrer) // "https://github.com/kanaka/mal"
window.location = "/kanaka/mal/tree/master/python"
console.log(history.length) // 4
console.log(document.referrer) // "https://github.com/kanaka/mal/tree/master/ada"
关于html - 通过 history.pushState() 更新 document.referrer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25003266/