How To Stop Browser Back In Modern Browser Using JavaScript?


Stop browser back


People keep on searching for this and end up finding something that does not work. Blocking the browser back functionality isn't that much difficult nowadays, you just to have the right code at the right time.



Now browsers are becoming more and more intelligent and thus we have access to manipulate the history of browser as we want. Here we are giving  a code snippet just for the right need.

What we want?

To stop the browser back functionality, so that when user tries to navigate back from the browser, he doesn't have a choice.

Why we want to stop browser's back functionality?

 Although this is not a good practice from UX perspective, but in some cases we need it badly and in that scenario we need a code that works across all browsers.

How we will do it?

Below given is the code where you just have to put your page name and it will work like a charm. Here we are taking Test.aspx as page name but you can rename it to your page name excluding the domain or directory part. Just name of the page.



var path = 'Test.aspx';
history.pushState(null, null, path + window.location.search);
window.addEventListener('popstate', function (event) {
    history.pushState(null, null, path + window.location.search);
});

window.location.search this helps in retaining the query parameters that your page might be having. It won't harm in case you don't have a query string params, just use the exact code.

This code will not work for IE < 10


So this is it about preventing the brower back functionality. Do let us know if it works for you. Do let us know your queries or any suggestion.

Happy Reading!

Comments

  1. this only works in chrome if inspect element is open otheriwse it's not working ...code is working fine in mozilla.

    please help...

    ReplyDelete
  2. Same problem as Pooja sais... The code only works when executed from Chrome console

    ReplyDelete
    Replies
    1. Try calling this code inside window.onload = function(){
      //place the code here
      }

      Hope this helps, let us know

      Delete

Post a Comment

Hey there, liked our post. Let us know.

Please don't put promotional links. It doesn't look nice :)

Popular posts from this blog

Create Android Apps - Getting Started

Polymorphism in Kotlin With Example