html5 – 通过history.pushState()更新document.referrer

我在我的ajax-app中使用pushStates从一个页面”导航到另一个页面”.现在,我想看看我来自哪个页面.但是document.referrer总是返回“”.或者,当我从另一个页面(链接的位置)打开我的应用程序时,我从另一个页面获取了URL.

不应该这些线……

history.pushState({},“Some title”,“/ some / valid / url / 1”);

history.pushState({},“/ some / valid / url / 2”);

…产生这样的推荐人:

http://somedomain.com/some/valid/url/1

换句话说:有没有办法相应地设置document.referrer,或者至少将其重置为“”?

注意:我正在寻找解决方案而不在某些变量中缓存以前的URL.我需要一些真正改变document.referrer的东西,因为我无法改变依赖它的脚本.

解决方法

简答:使用window.location而不是history.pushState

更长的答案:

document.referrer根据MDN:“如果用户直接导航到页面(不通过链接,但是,例如,通过书签),则值为空字符串”

直接操纵历史状态不会被视为跟随链接.您可以通过更新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"

相关文章

HTML5和CSS3实现3D展示商品信息的代码
利用HTML5中的Canvas绘制笑脸的代码
Html5剪切板功能的实现
如何通过HTML5触摸事件实现移动端简易进度条
Html5移动端获奖无缝滚动动画实现
关于HTML5和CSS3实现机器猫的代码