set alert on clicking the back button from the page

To implement an alert when the user clicks the back button in the browser, you can utilize the onbeforeunload event. This event is triggered when the user navigates away from the page, including when they click the back button. Here’s how you can implement it in JavaScript:

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

When the user tries to leave the page by clicking the back button or closing the browser tab/window, this script will display a confirmation dialog with the message “Are you sure you want to leave?”. The user can then choose to stay on the page or proceed with leaving.

Leave a comment

Your email address will not be published. Required fields are marked *