简体   繁体   中英

How to redirect user to another page once he has clicked the browser back button in JavaScript

What I am trying to achieve is to redirect the user to yahoo's page once he has clicked the browser's back button. Here is my attempt, currently nothing happens:

window.addEventListener('popstate', function() {
    var lastVisitedUrl = window.history.go(-1);
    window.history.replaceState(lastVisitedUrl , "Sample Title", "/yahoo.com");
    window.location.href.back()
});

How can I make the redirection once the browser back button is clicked?

Try this works properly

window.history.pushState({page: 1}, "", "");

window.onpopstate = function(event) {
    if(event){
        window.location.href = 'https://www.yahoo.com';
       
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM