检测页面是否从后退按钮加载 [英] Detect if page is load from back button

查看:106
本文介绍了检测页面是否从后退按钮加载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法检测当前页面是否来自后退按钮?

Is there any way to detect if current page came from back button?

我想只在当前页面来自后退按钮时从cookie加载数据。

I want to load data from cookie only if current page came from back button.

推荐答案

当用户返回页面时,会保留任何可见的表单数据,同时重置任何JavaScript变量。我说'可见'表单数据,因为隐藏字段似乎不会被保留,但隐形输入是。

When a user goes back a page, any visible form data is preserved, while any JavaScript variables are reset. I say 'visible' form data, as hidden fields seem not to be preserved, but invisible inputs are.

您可以使用此优势来检测是否页面是初始加载,或者之前已经加载过,例如从后退按钮单击。

You can use this to your advantage in order to detect whether the page was an initial load, or had already been loaded previously such as from a back button click.

创建一个带有值的不可见输入字段(不是隐藏类型)为'0',并在DOM ready loader中检查该值是否已设置为'1';如果您知道页面已经加载,例如从后退按钮;如果它仍然是'0'那么页面最初是第一次加载,将值设置为'1'。

Create a invisible input field (not type 'hidden') with a value of '0', and within a DOM ready loader check to see if the value has been set to '1'; if it has you know the page has already been loaded, such as from a back button; if it is still '0' then the page has initially loaded for the first time, set the value to '1'.

注意:这有点微妙了它的工作方式,可能不适用于所有浏览器;我在构建它时考虑到了Chrome。

Note: This is a bit delicate in the way it works, and probably doesn't work in all browsers; I built it with Chrome in mind.


  • 需要加载DOM;并非所有准备好的功能都有下面有一个
    ,JQuery准备好了;但是(我的实例中的function(){})却没有。

  • 输入不能是type =hidden。设置style =display:none;改为输入

<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>

这篇关于检测页面是否从后退按钮加载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆