-2

I want to disable the browser's back button. I have tried some javascript codes to implement the same. But those codes didn't meet my requirements. It works in firefox but not working in chrome and edge. Sometimes it works all the three but randomly working and not working.

Can anybody share me the script disable the back button in all browsers without flaws like random behaviour.

Here I showed some scripts I have tried

history.pushState(null, null, window.location.href);
history.back();
window.onpopstate = () => history.forward();

history.pushState(null, null, location.href);
history.back();
history.forward();
window.onpopstate = function () { history.go(1); };
kowshiga
  • 11
  • 1
  • 4
  • 1
    Does this answer your question? [How can I stop the browser back button using JavaScript?](https://stackoverflow.com/questions/12381563/how-can-i-stop-the-browser-back-button-using-javascript) – lusc Feb 19 '22 at 08:05

1 Answers1

3

You can refer to the following code. I test the code sample in Edge, Chrome and Firefox, it works well.

Save this file as a.html for the first page:

<!DOCTYPE html>
<html>
<head>
    <title>First Page</title>
    <script type="text/javascript">
        function preventBack() {
            window.history.forward();
        }
        setTimeout("preventBack()", 0);
        window.onunload = function () { null };
    </script>
</head>
<body>
    <h3>This is first page</h3>
    <a href="b.html">Goto second Page</a>
</body>
</html>

Save this file as b.html for the second page:

<!DOCTYPE html>
<html>
<head>
    <title>
        Blocking Back Button using javascript
    </title>
</head>
<body>
    <h3>This is second page</h3>
    <p>
        On this page, back button functionality is disabled.
    </p>
</body>
</html>

Run a.html and click to navigate to b.html. Then click browser's back button on b.html, it won't navigate to a.html.

Yu Zhou
  • 11,532
  • 1
  • 8
  • 22