javascriptmodal-dialogconfirm

Create confirm JavaScript for when users try to leave page without saving


I am trying to make it so that if a user makes changes to a page and then tries to leave the page without saving, a popup message will appear with an "OK" button (no "Cancel" button). Clicking the "OK" button, closes the message. The user must click the "Save" button or they will keep getting the message, prohibiting them from leaving the page until the "Save" button is clicked. By leave the page, I mean keeping them from navigating to another tab or menu item within the site...if they click any other link on the page, it would give them the popup. They can leave they site at anytime.

I am thinking I need JavaScript modal dialog to get rid of the Cancel button but am a bit uncertain of the implementation.

Currently, I am using r = confirm (see below) but it has the cancel button plus it gives the option for users to leave the page if they click "OK". I do not want them to be able to leave the page without clicking the "Save" button or they would have to close the entire window.

Any help/explanation is very much appreciated as I am very new to this. Thank you.

if (typeof unsaved != 'undefined') {
if (unsaved == true) {
var r = confirm("Please click Update. Unsaved changes will be lost.");
if (r == false) {
     saveNeeded = "true";
     }
     else { saveNeeded = "false"; }
 }
}

Solution

  • Take a look at onBeforeUnload.

    You won't be able to force a user to stay on the website, however it will provide a pop up window with the 'Leave' and 'Stay' buttons when they attempt to close the window. All major web browsers allow the user to leave any webpage at will, and the most you can do is warn them. onBeforeUnload is probably the best cross-browser solution you will achieve to give users a chance to stay on the site and save their changes before leaving.

    <script language="JavaScript">
        window.onbeforeunload = confirmExit;
        function confirmExit() {
            return "Please click Update. Unsaved changes will be lost.";
        }
    </script>
    

    It would be very bad practice to attempt to lock a user to your website without an option of leaving, which is why it is not supported by any major web browsers. If it is so important that you MUST force the user to do something (and you have the right to as a company or such), you should use another platform or write a custom plugin to the user's web browser. But for general use, you can't lock their browser.