demand

Sometimes when we’re working on a project, we come across a scenario like this:

Return to the specified page instead of returning by history

But we can’t stop the user from hitting the browser’s back button or the phone’s physical back button.


solution

Use the popState event to listen for the return

pushHistory();
window.addEventListener("popstate".function(e) {     
    window.location.href = 'http://www.baidu.com'; // Return to baidu},false);
function pushHistory(){    
    var state = {      
        title: "title",         
        url: "#"    
    };     
    window.history.pushState(state, "title"."#"); 
}Copy the code

Note: The above method works fine on PC and Android, but there is a problem on ios, where the popState event is immediately executed


Ios returns a solution that executes the popState event immediately

Page A -> B ->C. When page B returns, it needs to return to the specified page, such as Baidu.

Problem Description:

On ios, when page C returns, the popState event is executed immediately, leading to a direct jump to Baidu.

Solutions:

Processing via PagesHow events

var bool = false; // Define a variable window.addeventListener ('pageshow'.function () {            
    bool = false; Bool is set to bool when entering the pagefalseTo prevent ios from performing popState immediatelysetTimeout(function(){// Timer delay sets bool totrue            
        bool = true;        
    },500)    
});    

pushHistory();    
window.addEventListener("popstate".function(e) {         
    if(bool){            
        window.location.href = 'http://www.baidu.com';         
    };    
}, false);    

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