JS to prevent user from navigation away from current html page

Posted on Updated on

Here is a simple js script to prevent a user from navigating away from the current html page. What this script does is that the user will be shown a dialog box when they try to navigate away from the current page(page refresh or close browser). This could be very useful while performing critical processes through ajax and you don’t want user to navigate away from the current page in the middle of the process. Anyways you can’t stop user from closing the browser though :P, if they press the “leave page” button on confirmation, then the browser would eventually close. Afterall Users are users 🙂

This script will show confirmation dialog when navigating away from page. So put this script on the page or at the start of the ajax call.

window.onbeforeunload = function() { return "Are you sure you want to leave this page?"; };


leave page confirmation
Leave page confirmation Dialog

This script will remove the confirmation dialog. Put this script when you are done processing and you don’t mind user leaving the page.

window.onbeforeunload = null;

Thank you for reading this tuto.
Hope this was useful to you 🙂