window.history对象

1. 只读属性

1. length

表示当前窗口访问过的url的数量;或者手动pushState之后的length。

2.state

表示当前地址栏中网址对应的状态。

2. 方法

1. 刷新网页-back()、forward()、go(num)

1. 回退一个地址,相当于浏览器的后退键;对第一个网址无效

history.back() 
// 或者
history.go(-1)

2. 前进一个地址,相当于浏览器的前进键;对最后一个网址无效

history.forward()
// 或者
history.go(1)

3. 根据参数大小进行前进或者回退的个数

go(n);
当n>0时,前进n个历史记录;当n>history.length时,失效。
go(0); 刷新当前页面
当n<0时,后退n个历史记录;当n>history.length时,失效。

2.不刷新网页-pushState()

可以改变当前地址栏的url,且在历史记录中添加一条; 但是不会刷新页面。

window.history.pushState(state, title, url)
//  state是一个和url关联的值,在popstate事件中可能有用
//  title一般空字符串,也可以设置一个其他值
//  url可以只写域名后面的部分,表示在当前域名下修改;也可以写绝对路径

而且,pushState也不会触发popstate, hashchange事件。

为了安全,url只能是同域名网址。

3. 不刷新页面-replaceState(state,title,url)

功能是修改history对象的当前记录。其他参数和pushState相同。

它也不会刷新页面,不会触发popstate, hashchange监听事件。

3. 事件

浏览器路由有两种。HashRouter和BrowserRouter。浏览器中监听这两种路由变化的事件对应也有两种。

1. popstate事件

监听browserRouter的变化。

顾名思义,它只监听history的出栈的操作。history.pushState()方法入栈,每调用一次增加一条history。而出栈是指访问所有history列表中出现过的路由。

而访问历史记录触发popstate事件,只能通过以下两种方式。

触发方式

1)手动单击浏览器前进后退按钮

2)代码调用history.back(), history.forward(), history.go(n)

应用

可以通过自定义的pushState方法, onpopstate事件,监听实现不刷新页面根据browserRouter更改页面内容的功能。

<body>
  <input />
  <button onclick="push('/a')">/a</button>
  <button onclick="push('/b')">/b</button>
  <button onclick="push('/c')">/c</button>
  <div id="content" style="border: 3px solid red;  300px; height: 300px"></div>
  <script>
    const content = document.getElementById('content');
    function push(url) {
      // 该方法本身只能实现路由的变化,无法改变页面内容
      // 需要修改该方式实现修改页面的功能
      window.history.pushState({to: url}, null, url);
    }
    // 入栈通过history.pushState()方法
    // 出栈触发通过浏览器前进后退键;或者history.back()/history.forward()/history.go()
    window.onpopstate = function(e) {
      content.innerHTML = `页面${e.state.to}`
    }
    let oldPushState = window.history.pushState;
    window.history.pushState = function(state, title, url) {
      // 覆写方法时,一定要注意可能发生this变化
      oldPushState.call(window.history, {to: url}, null, url);
      content.innerHTML = `页面${state.to}`;
    }
  </script>
</body>

2. hashchange事件

监听hashRouter的变化。路由改变不会刷新页面,只修改hash值关联的内容。

根据hashChange事件的监听,修改hash值对应的页面的内容。

<body>
  <a href="#a">跳转到a</a>
  <a href="#b">跳转到b</a>
  <div id="content" style="border: 3px solid red;  300px; height: 300px"></div>
  <script>
    window.addEventListener('hashchange', (e) => {
      const content = document.getElementById('content');
      content.innerHTML = `这是页面${window.location.hash.slice(1)}`
    })
  </script>
</body>

触发方式:

1)手动单击浏览器前进后退键过程中,如果有hash内容变换,触发

2)history.back(), history.forward(), history.go(n)同理

3) 手动点击hash链接

4) 给window.location.hash赋值

location.hash = 4
原文地址:https://www.cnblogs.com/lyraLee/p/11992785.html