js怎么解决popstate多个页面连续返回问题

JavaScript032

js怎么解决popstate多个页面连续返回问题,第1张

在WebApp或浏览器中,会有点击返回、后退、上一页等按钮实现自己的关闭页面、调整到指定页面、确认离开页面或执行一些其它操作的需求。可以使用 popstate 事件进行监听返回、后退、上一页操作。

一、简单介绍 history 中的操作

1.window.history.back(),后退

2.window.history.forward(),前进

3.window.history.go(num),前进或后退指定数量历史记录

4.window.history.pushState(state, title, utl),在页面中创建一个 history 实体。直接添加到历史记录中。

参数:state:存储一个对象,可以添加相关信息,可以使用 history.state 读取其中的内容。

title:历史记录的标题。

url:创建的历史记录的链接。进行历史记录操作时会跳转到该链接。

5.window.history.replaceState(),修改当前的 history 实体。

6.popstate 事件,history 实体改变时触发的事件。

7.window.history.state,会获得 history 实体中的 state 对象。

二、使用方法

取消默认的返回操作:

1.添加一条 history 实体作为替代原来的 history 实体

function pushHistory(){  var state = {

      title: "title",

      url: "#"    

   }

 window.history.pushState(state, "title", "#") 

}

pushHistory()

2.监听 popstate 事件

window.addEventListener("popstate", function(){    //doSomething}, false)

三、注意事项

1.每次返回都会消耗一个 history 实体,若用户选择取消离开,则需要继续 pushState 一个实体

2.pushState 只能一个实体,多个实体返回会出错。使用 window.history.state 查询是否存在添加的实体。

在这里我们把history简化成一个链表来讨论 , 以下红色数字为 url 当前位置

引起history变化的动作有三类:

页面点击链接,js控制location.href跳转等,我们给这类起名为硬跳转

pushState

replaceState

引起当前位置在表中的变化有两种: 前进、后退

硬跳转:

1)history 表如上,通过回退的方式使当前 url 在 2 处

2)触发硬跳转,history变为如下:

当前位置为 3 ,url为硬跳转的链接

页面:

1)立即变化

2)接下来的前进后退,页面按 history 中的url顺序变化

pushState:

1)history 表如上,当前位置在 2 处,触发pushState方法

2)history 表如下:

当前位置为 3 ,url为push进来的链接

页面:

1)不会立即变化,还是 2

2)接下来的前进后退,1与2都会正常加载页面,但当url到3 时,页面仍是 2,这里没有找到原因,存疑!!!!!

replaceState:

1)history 表如上,当前位置在 2 处,触发 replaceState 方法

2)history 表如下:

当前位置在 2 处,且 url 为 replace 进来的 新url

页面:

1)页面不会立即变化

2)接下来的前进后退,页面按 history 中的url顺序变化

popstate:

需要注意的是,仅仅调用popstate方法或replaceState方法 ,并不会触发该事件,只有用户点击浏览器倒退按钮和前进按钮,或者使用JavaScript调用back、forward、go方法时才会触发。另外,该事件只针对同一个文档,如果浏览历史的切换,导致加载不同的文档,该事件也不会触发。

$(document).ready(function(e) {

var counter = 0

if (window.history &&window.history.pushState) {

$(window).on('popstate', function () {

window.history.pushState('forward', null, '#')

window.history.forward(1)

alert("不可回退")

})

}

window.history.pushState('forward', null, '#')//在IE中必须得有这两行

window.history.forward(1)

})