Val*_*ter 16 javascript firefox internet-explorer
有没有办法检测当前页面是否来自后退按钮?
我想只在当前页面来自后退按钮时从cookie加载数据.
Rad*_*erz 17
当用户返回页面时,将保留任何可见的表单数据,同时重置任何JavaScript变量.我说'可见'表单数据,因为隐藏字段似乎不被保留,但隐形输入是.
您可以使用此优势来检测页面是初始加载,还是先前已加载,例如从后退按钮单击.
创建一个值为'0'的不可见输入字段(不是'hidden'类型),并在DOM ready loader中检查该值是否已设置为'1'; 如果您知道页面已经加载,例如从后退按钮; 如果它仍为"0",则页面首次加载,将值设置为"1".
注意:它的工作方式有点微妙,可能并不适用于所有浏览器; 我用Chrome构建了它.
.
<input id="backbuttonstate" type="text" value="0" style="display:none;" />
<script>
document.addEventListener('DOMContentLoaded', function () {
var ibackbutton = document.getElementById("backbuttonstate");
if (ibackbutton.value == "0") {
// Page has been loaded for the first time - Set marker
ibackbutton.value = "1";
alert('First time load');
} else {
// Back button has been fired.. Do Something different..
alert('Previously loaded - Returned from Back button');
}
}, false);
</script>
Run Code Online (Sandbox Code Playgroud)
小智 9
使用 pageshow 事件来检测后退或前进按钮:
$(window).bind("pageshow", function(event) {
if (event.originalEvent.persisted) {
Alert("User clicked on back button!");
}
});
Run Code Online (Sandbox Code Playgroud)
有关更多详细信息,您可以在此处查看pageshow事件。
小智 7
为了更简单地进行检查,有“ 导航时序API规范”(已不建议使用,但得到广泛支持)和“ 导航时序2级API规范”(工作草案,受主要浏览器支持)
if (window.performance) {
var navEntries = window.performance.getEntriesByType('navigation');
if (navEntries.length > 0 && navEntries[0].type === 'back_forward') {
console.log('As per API lv2, this page is load from back/forward');
} else if (window.performance.navigation
&& window.performance.navigation.type == window.performance.navigation.TYPE_BACK_FORWARD) {
console.log('As per API lv1, this page is load from back/forward');
} else {
console.log('This is normal page load');
}
} else {
console.log("Unfortunately, your browser doesn't support this API");
}
Run Code Online (Sandbox Code Playgroud)
if (window.performance && window.performance.navigation.type == window.performance.navigation.TYPE_BACK_FORWARD) {
$('.formName').get(0).reset();
}
Run Code Online (Sandbox Code Playgroud)
小智 -1
基本上,由于浏览器限制,您不能。HTML5历史记录API,导航到后台页面时将触发onpopstate事件。但即使您使用应用程序导航,这也会触发。
替代解决方案请参阅 -如何检测浏览器后退按钮事件 - 跨浏览器
| 归档时间: |
|
| 查看次数: |
10836 次 |
| 最近记录: |