Hemanshu Patel
Hemanshu Patel

Reputation: 46

trying to redirect to some page when pressing browser back button but not working

Below is my code:

window.addEventListener("beforeunload", function(event) {  <br/>
    event.preventDefault();  <br/>
    event.returnValue = '';  <br/>
    window.location.href = 'https://google.co.in';  <br/>
    return false;  <br/>
});

Upvotes: 1

Views: 290

Answers (2)

Ahmed Ali
Ahmed Ali

Reputation: 1966

There is an error in window.location.href('https://google.co.in') just replace this with window.location.href = 'https://google.co.in'; it will work. location.href is used like this given an link and another method is given below.

window.location.replace("http://www.google.com");

Events that trigger the beforeunload function:

  1. Navigating to another page directly in the browser or via a link.
  2. Closing the current browser window or tab page.
  3. Reloading the current page.
  4. Manipulating the URL of the currently loaded page through the location object from JavaScript.
  5. Invoking the window.navigate method.
  6. Invoking the window.open or the document.open method to open a document in the same window.


This code prevent the back button and replace the window to google.com

window.addEventListener( "pageshow", function ( event ) {
  var historyTraversal = event.persisted || 
                         ( typeof window.performance != "undefined" && 
                              window.performance.navigation.type === 2 );
  if ( historyTraversal ) {
    // Handle page restore.
   window.location.replace("http://www.google.com");
  }
});

Upvotes: 0

Simon
Simon

Reputation: 326

You can try to modify history, and use state to know if user go back

window.onpopstate = function(event) {
    if (event.state && event.state.redirect) {
       window.location.replace("http://www.google.com");
    }
};
history.replaceState({redirect: true}, "");
history.pushState({redirect: false}, "");

Upvotes: 1

Related Questions