• 利用popstate事件和window下的history对象处理浏览器跳转问题


    History 接口
    属性
    History.length 表示历史会话中元素的数目
    History.scrollRestoration 允许Web应用程序在历史导航上显式地设置默认滚动恢复行为。此属性可以是自动的(auto)或者手动的(manual)。
    History.state 返回一个表示历史堆栈顶部的状态的值。这是一种可以不必等待popstate 事件而查看状态而的方式。
    方法
    History.back()
    等同于history.go(-1)

    History.forward()
    等同于historygo(1)

    History.go()
    这个方法中如果参数超出范围或者不对就不会起效果

    History.pushState()
    pushState() 带有三个参数:一个状态对象,一个标题(现在被忽略了),以及一个可选的URL地址。下面将对这三个参数进行细致的检查

    function pushHistory() {  
      var state = {  
        title: "title",  
        url: "#"  
      };  
      window.history.pushState(state, "title", "#xx");  
     } 
    

    监听浏览器返回按钮

    function pushHistory() {  
        var state = {  
          title: "title",  
          url: "#"  
        };  
        window.history.pushState(state, "title", "#xx");  
    }
    pushHistory();
    window.addEventListener("popstate", function(e) {  
        console.log(e);
        alert("我监听到了浏览器的返回按钮事件啦");//根据自己的需求实现自己的功能  
    }, false);
    

    禁止返回上一页的一种方案

    history.pushState(null, null, document.URL);
    window.addEventListener("popstate",function(e) {  
        console.log(e);
        history.pushState(null, null, document.URL);
    }, false);
    

    这个其实就是利用pushState向浏览历史列表中插入当前页面,在点击后退前和点击时都插入一次,那样无论点前进还是后退永远都会留在这个页面了
    JS监听浏览器前进后退事件

    
    window.addEventListener('popstate', function(e) {
      init++
      if (init < 2) {
        router.beforeEach((to, from, next) => {
          let arr1 = to.path.split('/')
          console.log('aaaa...1111',arr1)
          let arr2 = from.path.split('/')
          console.log('bbbbb....22222',arr2)
          if (arr1.length === 2) {
            
            if (arr1[1].length === 0) {
              arr1.splice(1, 1)
              console.log('ccccc',arr1)
            }
          }
          if (arr2.length === 2) {
            if (arr2[1].length === 0) {
              arr2.splice(1, 1)
            }
          }
          if (arr1.length < arr2.length) {
            router.toGoBack()
          } else {
            router.toGoIn()
          }
          next()
        })
      }
    }, false)
    


    本文部分转载自:https://www.cnblogs.com/wancheng7/p/8542544.html

  • 相关阅读:
    RestTemplate与Gzip压缩
    在浏览器中异步下载文件监听下载进度
    springBoot中的所有配置属性(中文)
    Springboot应用中设置Cookie的SameSite属性
    客户端解析服务器响应的multipart/form-data数据
    springboot + querydsl 入门到会用
    MyBatis通过TypeHandler自动编解码对象的Json属性
    @Transaction注解失效的几种场景
    Elasticsearch 7.x配置用户名密码访问 开启x-pack验证
    搭建Elasticsearch可视化界面 Kibana
  • 原文地址:https://www.cnblogs.com/smart-girl/p/13030760.html
Copyright © 2020-2023  润新知