Welcome to a tutorial on how to disable the browser back functionality in Javascript. So the user has signed off, but is still able to access a cached version of the protected page by going back? Or you just want the user to stay on a page? I have compiled a list of solutions from the Internet in this guide, and share some of my thoughts – Read on!
TLDR – QUICK SLIDES
[web_stories_embed url=”https://code-boxx.com/web-stories/disable-back-javascript/” title=”Ways To Disable Back In Javascript” poster=”https://code-boxx.com/wp-content/uploads/2021/11/STORY-JS-20230518.webp” width=”360″ height=”600″ align=”center”]
Fullscreen Mode – Click Here
TABLE OF CONTENTS
JAVASCRIPT NO BACK
All right, let us now get into the possible ways to disable the “back button” in Javascript.
METHOD 1) PUSH-POP HISTORY STATE
1A) DUMMY PAGE
<a href="1b-state.html">Go To Next Page</a>
Nothing much on this dummy first page, just a link to go to the second page.
1B) PREVENT BACK WITH HISTORY STATE
<script>
// CREDITS : https://www.codexworld.com/how-to/disable-browser-back-button-using-javascript/
history.pushState(null, null, location.href);
window.onpopstate = () => history.go(1);
</script>
<div>You shall not hit back!</div>
For those who are new:
history.pushState(null, null, location.href)
Will add the current URL to the navigation history.window.onpopstate = () => history.go(1)
When the navigation history is changed, go forward. I.E. If the user goes back, this will force the user back to the current page.
METHOD 2) HISTORY FORWARD
2A) PREVENT BACK BY FORWARDING
<script>
// CREDITS : https://www.codeproject.com/Questions/149637/Disable-Browser-Back-Button-functionality-after-cl
function noBack() { history.forward(); }
noBack();
window.onload = noBack;
window.onpageshow = evt => { if (evt.persisted) { noBack(); }};
window.onunload = () => null;
</script>
<a href="2b-forward.html">Go To Next Page</a>
This is yet another ancient solution that has been passed down the ages.
- The star of the show here is actually
history.forward()
. - That is, if the user hits “back” from another page, this will force the user “forward”.
2B) DUMMY PAGE
<div>You shall not hit back!</div>
Nothing here once again, just a dummy page.
METHOD 3) FORCE RELOAD ONLY IF SIGNED OUT
<script>
// FORCE RELOAD (OR REDIRECT) IF THE USER HAS LOGGED OUT.
// CREDITS : https://web.dev/bfcache/
window.addEventListener("pageshow", evt => {
if (evt.persisted && !document.cookie.match(/my-cookie/)) {
location.reload();
// location.href = "LOGIN PAGE";
}
});
</script>
<div>This page will not show if:</div>
<ol>
<li>Is loaded from browser cache.</li>
<li>User is signed out (no cookie).</li>
</ol>
A modern solution that I don’t see many people use.
window.addEventListener("pageshow", evt => { ... });
Run the check when the page shows.if (evt.persisted && !document.cookie.match(/my-cookie/)) { REDIRECT }
Reload/redirect if the page is loaded from the browser cache and the user is no longer signed in (session cookie is cleaned out).
METHOD 4) WARN IF LEAVING PAGE
<script>
window.onbeforeunload = () => "Are you sure!?";
</script>
<a href="https://code-boxx.com">Warn before user navigates away.</a>
Well, as simple as it gets. Just warn the user before leaving the page.
DOWNLOAD & NOTES
Here is the download link to the example code, so you don’t have to copy-paste everything.
SORRY FOR THE ADS...
But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.
Buy Me A Coffee Code Boxx eBooks
EXAMPLE CODE DOWNLOAD
Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.
EXTRA BITS & LINKS
That’s all for the tutorial, and here is a small section on some extras and links that may be useful to you.
DOES IT WORK? WHICH IS THE BEST?
Sorry to disappoint the people who think “force forward” is a “perfect solution” – It does not work 100%, has never worked perfectly, and never will. There is simply no way to disable the back button entirely – Users can still right-click on the back button and go back, or just hit the back button multiple times.
As for what worked best for me in user login/logout – Checking the user session and cookie. A quick explanation and example in JS and PHP:
if (!document.cookie.match(/PHPSESSID/)) { location.href = "LOGIN"; }
- In all PHP library functions and API endpoints reserved for users –
if (!isset($_SESSION["user"])) { exit("NO PERMISSION"); }
COMPATIBILITY CHECKS
- Arrow Functions – CanIUse
- History API – CanIUse
- Page Show Event – CanIUse
- PageTransitionEvent API: persisted – CanIUse
Take extra note if you are working with ancient browsers.
LINKS & REFERENCES
- How to Disable Browser Back Button using JavaScript – Codex World
- Disable Browser Back Button functionality after click on Logout Button – Code Project
- Back/forward cache – Web Dev
INFOGRAPHIC CHEAT SHEET
THE END
Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!