how to restrict page leave in javascript
How to Restrict Page Leave in JavaScript
Have you ever been in a situation where you want to stop the user from leaving your web page accidentally? Well, it's possible with JavaScript. In this article, I will show you how to restrict page leave in JavaScript.
Method 1: Using the onbeforeunload Event
The onbeforeunload event gets triggered when a user tries to leave a web page. Therefore, we can use it to restrict users from leaving the page accidentally.
window.onbeforeunload = function() {
return "Do you really want to leave?";
};
The above code will trigger an alert message when the user tries to leave the page. However, this method has a significant drawback - it will trigger the alert message even if the user wants to close the window or reload the page. Therefore, we need a more refined solution.
Method 2: Using the addEventListener Method
We can use the addEventListener method to add an event listener to the window object. The listener will listen for the beforeunload event and trigger the alert message only if certain conditions are met.
window.addEventListener('beforeunload', function (e) {
if (someCondition) {
// Cancel the event
e.preventDefault();
// Chrome requires returnValue to be set
e.returnValue = '';
}
});
In the above code, we added a condition that needs to be met before triggering the alert message. If the condition is not met, the event will be canceled, and the user will be allowed to leave the web page freely.
Method 3: Using the Confirm Dialog Box
Another way to restrict page leave is by using the confirm dialog box. The confirm dialog box is a built-in JavaScript dialog box that prompts the user to confirm or cancel an action.
window.onbeforeunload = function() {
return confirm("Do you really want to leave?");
};
The above code will trigger the confirm dialog box when the user tries to leave the page. If the user clicks the "OK" button, it will allow the user to leave the page. However, if the user clicks the "Cancel" button, it will prevent the user from leaving the page.
These are some of the ways to restrict page leave in JavaScript.