美文网首页
监听浏览器的后退事件

监听浏览器的后退事件

作者: 晴雨稀兮 | 来源:发表于2018-07-28 16:01 被阅读0次

    1.window的popstate事件

    监听浏览器回退事件,主要依赖于监听:window的popstate事件,因为浏览器在被点击“后退”或者“前进"按钮时,都会触发popstate事件。
    因此,可以在

    window.on('popstate', function(){
        // to do
    })
    

    2.window的pushState事件

    window的pushState事件,是实现往浏览器的历史记录中添加记录,但是不刷新当前页面的功能,即没有发生任何请求导致window.location.href发生变化。此方法有三个参数,分别是:

    state:要新添加的记录的状态,是个对象
    title:新页面的title,可以为空
    href:新页面的url
    

    3. 监听浏览器后退的实现

    3.1 将当前页面的URL后面加#
     $(document).ready(function (e) {
            if (window.history && window.history.pushState) {
                $(window).on('popstate', function () {
                    self.location="/credit/miniprogram/copartner/bankList"; //如查需要跳转页面就用它
                });
            }
            window.history.pushState('forward', null, '#'); //在IE中必须得有这两行
            window.history.forward(1);
        }); 
    
    3.2 将当前页面压入历史记录中
      "pushState" in window.history && (
        window.history.pushState({
            title: document.title,
            url: location.href
        }, document.title, location.href),
          //setTimeout(function () {
              window.addEventListener("popstate", function (a) {
                self.location="/credit/miniprogram/copartner/bankList";                    
              })
          //})
        );
    

    PS: 不是特别明白pushState的作用,这里只是代码的搬运工,记录一下,后续修改吧。

    相关文章

      网友评论

          本文标题:监听浏览器的后退事件

          本文链接:https://www.haomeiwen.com/subject/yseomftx.html