0

I want to prevent browser back button to not go to previous page.
For this I tried below code:

<script type = "text/javascript" >
        function preventBack() { window.history.forward(); }
        setTimeout("preventBack()", 0);
        window.onunload = function () { null };
    </script>

but when I click on browser back button continuously 2-3 times at one go, it again redirects to previous page. So my above code fails.
I don't want user to go to previous page.

I tried this code as well:

<script>

    $(document).ready(function () {
        function disableBack() { window.history.forward() }

        window.onload = disableBack();
        window.onpageshow = function (evt) { if (evt.persisted) disableBack() }
    });

</script>

but this code is removing the scroller from browser and I am unable to scroll the page.

Please reply some solution. I tried searching many articles but could not find any solution.

timz_123
  • 435
  • 1
  • 9
  • 47
  • I highly recommend considering some other options. In most cases, hijacking the back button like this is bad UX, which is probably why you're getting downvoted. Users shouldn't feel like a website is working against them, or "breaking" their browser. For example. if going back puts your app in a bad state, have the previous page render a message explaining why. – edan Jan 25 '22 at 16:39

1 Answers1

0

Try this

<script type="text/javascript">
        window.history.forward(1);
 </script>

Or you may read this

Community
  • 1
  • 1
Heinz Siahaan
  • 355
  • 2
  • 10
  • For all solutions I am facing the issue that when I click on browser back button continuously 2-3 times at one go, it again redirects to previous page. So my above code fails. Please reply some other solution which work without this issue? – timz_123 Aug 07 '15 at 01:31
  • I set that in header of my pages and nothing wrong until now. Maybe you can leave your so called attribute(`windows.unload`,`$(document)`, etc) and set it in header without those attributes. Sometimes simple thing is the answer. – Heinz Siahaan Aug 07 '15 at 02:39