sag*_*ian 7 javascript firefox javascript-events popstate
我有一个简单的网页,即:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>History hacks</title>
<script>
window.onpopstate = function (e) {
alert("location: " + document.location + ", state: " + JSON.stringify(e.state));
}
window.onload = function (e) {
alert('page loaded');
}
</script>
</head>
<body>
<p> <a href="http://www.yahoo.com">Yahoo</a> <a href="#part1">Part 1</a></p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
现在关于Chrome和Firefox如何触发popstate事件有很多不同之处(当我开始测试IE时,我不禁想到我正在反对的事情),但是在这里给我带来问题的是Chrome会触发一个popstate只要我点击这两个链接中的任何一个,然后当我点击后退按钮时再次发生事件.Firefox将触发更改散列部分的链接事件(仅在哈希链接相同时才第一次),如果单击Yahoo链接然后单击后退按钮,则根本不会触发它.
那么有一种方法我可以在Firefox中告诉用户刚刚点击回来并从另一个域上的完全不同的站点返回我的页面吗?还有另一个可以在Firefox中用于此目的的事件吗?(当我从yahoo.com返回时,加载事件不会被触发.)
Sea*_*gan 11
要popstate使用后退(或前进)按钮进入初始页面加载时获取事件,请使用replaceState()like
window.onload = function(e) {
history.replaceState(null, null, document.URL);
}
Run Code Online (Sandbox Code Playgroud)
要忽略popstateChrome在加载页面时生成的初始值,您可以在调用pushState/ 时标记状态replaceState,例如
history.pushState({myTag: true}, null, url);
Run Code Online (Sandbox Code Playgroud)
然后您的popstate处理程序只是过滤myTag
window.onpopstate = function(e) {
if (!e.state.myTag) return; // none of my business
// code to handle popstate
}
Run Code Online (Sandbox Code Playgroud)
您可以将这两者结合起来,实现一个简单的跨浏览器解决方案:
window.onpopstate = function(e) {
if (!e.state.myTag) return; // none of my business
// code to handle popstate
}
window.onload = function(e) {
history.replaceState({myTag: true}, null, document.URL);
}
Run Code Online (Sandbox Code Playgroud)
@Boris Zbarsky详细介绍了bfcache.我没有想过如何将它与我的方法结合起来.我只是通过添加页面处理程序来禁用它unload
window.onunload = function(e) { }
Run Code Online (Sandbox Code Playgroud)
pageshow如果您希望在返回时显示页面时收到通知,即使该页面已缓存在页面缓存中,您可能正在寻找该事件。
请注意,如果没有加载事件,也意味着页面仍然具有与导航离开时完全相同的 DOM 和脚本执行环境。基本上,就好像用户切换了标签一段时间,而不是导航。
那么考虑到这一点,在这种情况下你还想参加活动吗?当用户切换回包含您的页面的选项卡时,您是否会收到您要查找的事件?
| 归档时间: |
|
| 查看次数: |
5196 次 |
| 最近记录: |