The main use of historyPopstate listeningAs well aspushstateUsing popState to listen for changes in Historty to ensure that the interface is always in the Final and MeanSure layers and therefore cannot reach the first access interface to prevent H5 from returning to the implementation details as shown below
<! DOCTYPEhtml>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>goto1</title>
</head>
<body>
<h1>This is goto1</h1>
<a href='goto2.html'>Go to 2</a>
</body>
<script>
var i = 0;
doIt()
console.log(1,history.length)
// Encapsulate the general operation, jump to another page
function toUrl(url){
// Jump back to the vertex first to prevent multiple record additions
window.history.pushState({target: "Final",}, "", location.href);
location.href=url;
}
// Encapsulate the general operation, back to the previous level
function back() {
let backCount=history.state.target == "Final"? -3: -2;
history.go(backCount);
}
// The general operation of encapsulation stays on this page
function stay() {
history.forward();
}
// The actual interception operation
function doIt() {
// Add 500 ms delay here. The purpose is to wait for the history to change before adding the empty address, so that the empty address can be added to the top of the stack accurately, in case of error
setTimeout(() = > {
if(! (history.state && history.state.target =="Final")) {
window.history.pushState({target: "MeanSure".random: Math.random()}, "", location.href);
window.history.pushState({target: "Final".random: Math.random()}, "", location.href);
console.log('Add done',history.state)
}
window.addEventListener("popstate".function (e) {
console.log('Listening for page action',history.state)
console.log(5,history.length)
if (e.state && e.state.target == "MeanSure") {
// You can call some custom operations, such as pop-up prompts. Finally, you can call any of the above three functions to determine whether to stay on this page, go back, or jump to another page after the current custom operations are completed
// doSomething();
stay();// The action will stay on this page
//back(); This operation falls back to the previous level without side effects
//toUrl ('http://www.baidu.com'); This operation will perform the defined operation after the jump to Baidu}},false);
history.back() // Automatically triggers popState
}, 2000);
}
</script>
</html>
Copy the code