更新文档.通过history.pushState()引用



我在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"

最新更新