浏览器返回按钮的onpopstate事件,pushstate事件和相关知识

858 阅读1分钟

onpopstate事件: 点击浏览器后退会触发popstate事件

@HostListener('window:popstate', ['$event'])
onPopState(e) {
  console.log(‘click back----------’+JSON.stringify(history.state));
}

pushstate():

添加 一个历史条目, 常与onpopstate事件联合使用。只改变地址栏里的url 不重新加载对应的页面

页面关系 a.html---- b.html-----c.html

背景操作: a.html----点击a.html上的某个跳转连接----b.html
b.html
<div click='clickbtn'>点我pushstate<div>
clickbtn(){
const state = { 'page_id': 1, 'user_id': 5 }
const title = ''
const url = 'c.html'

history.pushState(state, title, url)

console.log(‘init----------’+JSON.stringify(history.state));
}

@HostListener('window:popstate', ['$event'])
onPopState(e) {
  console.log(‘click back----------’+JSON.stringify(history.state));
}

效果:

  1. 当前页面为 http://localhost:8080/mall/b.html, 点击按钮后,地址栏变为 http://localhost:8080/mall/c.html 但显示内容仍然是b.html 不会去加载c.html,甚至都不检查c.html 存不存在。
  2. 控制台打印出 init----------{ 'page_id': 1, 'user_id': 5 }
  3. 点击后退按钮
  4. 当前页面变为http://localhost:8080/mall/ b.html
  5. 控制台打印出 click back----------{"navigationId":2} 这个是state 自带的默认键值对 并没有打印出自定义的键值对

replaceState():

修改当前的返回历史的属性,而不是添加新的。只改变地址栏里的url,不重新加载对应的页面

页面关系 a.html---- b.html-----c.html

背景操作: a.html----点击a.html上的某个跳转连接----b.html
b.html
<div click='clickbtn'>点我replacestate<div>

clickbtn(){
const state = { 'page_id': 1, 'user_id': 5 }
const title = ''
const url = 'b.html'

history.replaceState(state, title, url)

console.log(‘init----------’+JSON.stringify(history.state));
}


@HostListener('window:popstate', ['$event'])
onPopState(e) {
  console.log(‘click back----------’+JSON.stringify(history.state));
}

效果:

  1. 当前页面为 http://localhost:8080/mall/b.html, 点击按钮后,地址栏变为 http://localhost:8080/mall/c.html 但内容仍然是显示b.html 不会去加载c.html,甚至都不检查c.html 存不存在。
  2. 控制台打印出 init----------{ 'page_id': 1, 'user_id': 5 }
  3. 点击后退按钮
  4. 当前页面变为http://localhost:8080/mall/ a.html
  5. 控制台打印出 click back----------{"navigationId":2} 这个是state 自带的默认键值对 并没有打印出自定义的键值对