Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6542477
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 25, 20262026-05-25T11:13:56+00:00 2026-05-25T11:13:56+00:00

I have some pages with forms in my application. How can I secure the

  • 0

I have some pages with forms in my application.

How can I secure the form in such a way that if someone navigates away or closes the browser tab, they should be prompted to to confirm they really want to leave the form with unsaved data?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-25T11:13:57+00:00Added an answer on May 25, 2026 at 11:13 am

    Short, wrong answer:

    You can do this by handling the beforeunload event and returning a non-null string:

    window.addEventListener("beforeunload", function (e) {
        var confirmationMessage = 'It looks like you have been editing something. '
                                + 'If you leave before saving, your changes will be lost.';
    
        (e || window.event).returnValue = confirmationMessage; //Gecko + IE
        return confirmationMessage; //Gecko + Webkit, Safari, Chrome etc.
    });
    

    The problem with this approach is that submitting a form is also firing the unload event. This is fixed easily by adding the a flag that you’re submitting a form:

    var formSubmitting = false;
    var setFormSubmitting = function() { formSubmitting = true; };
    
    window.onload = function() {
        window.addEventListener("beforeunload", function (e) {
            if (formSubmitting) {
                return undefined;
            }
    
            var confirmationMessage = 'It looks like you have been editing something. '
                                    + 'If you leave before saving, your changes will be lost.';
            
            (e || window.event).returnValue = confirmationMessage; //Gecko + IE
            return confirmationMessage; //Gecko + Webkit, Safari, Chrome etc.
        });
    };
    

    Then calling the setter when submitting:

    <form method="post" onsubmit="setFormSubmitting()">     
        <input type="submit" />
    </form>
    

    But read on…

    Long, correct answer:

    You also don’t want to show this message when the user hasn’t changed anything on your forms. One solution is to use the beforeunload event in combination with a "dirty" flag, which only triggers the prompt if it’s really relevant.

    var isDirty = function() { return false; }
    
    window.onload = function() {
        window.addEventListener("beforeunload", function (e) {
            if (formSubmitting || !isDirty()) {
                return undefined;
            }
            
            var confirmationMessage = 'It looks like you have been editing something. '
                                    + 'If you leave before saving, your changes will be lost.';
    
            (e || window.event).returnValue = confirmationMessage; //Gecko + IE
            return confirmationMessage; //Gecko + Webkit, Safari, Chrome etc.
        });
    };
        
    

    Now to implement the isDirty method, there are various approaches.

    You can use jQuery and form serialization, but this approach has some flaws. First you have to alter the code to work on any form ($("form").each() will do), but the greatest problem is that jQuery’s serialize() will only work on named, non-disabled elements, so changing any disabled or unnamed element will not trigger the dirty flag. There are workarounds for that, like making controls readonly instead of enabling, serializing and then disabling the controls again.

    So events seem the way to go. You can try listening for keypresses. This event has a few issues:

    • Won’t trigger on checkboxes, radio buttons, or other elements that are being altered through mouse input.
    • Will trigger for irrelevant keypresses like the Ctrl key.
    • Won’t trigger on values set through JavaScript code.
    • Won’t trigger on cutting or pasting text through context menus.
    • Won’t work for virtual inputs like datepickers or checkbox/radiobutton beautifiers which save their value in a hidden input through JavaScript.

    The change event also doesn’t trigger on values set from JavaScript code, so also won’t work for virtual inputs.

    Binding the input event to all inputs (and textareas and selects) on your page won’t work on older browsers and, like all event handling solutions mentioned above, doesn’t support undo. When a user changes a textbox and then undoes that, or checks and unchecks a checkbox, the form is still considered dirty.

    And when you want to implement more behavior, like ignoring certain elements, you’ll have even more work to do.

    Don’t reinvent the wheel:

    So before you think about implementing those solutions and all required workarounds, realize you’re reinventing the wheel and you’re prone to running into problems others have already solved for you.

    If your application already uses jQuery, you may as well use tested, maintained code instead of rolling your own, and use a third-party library for all of this.

    jquery.dirty (suggested by @troseman in the comments) provides functions for properly detecting whether a form has been changed or not, and preventing the user from leaving the page while displaying a prompt. It also has other useful functions like resetting the form, and setting the current state of the form as the "clean" state. Example usage:

    $("#myForm").dirty({preventLeaving: true});
    

    An older, currently abandoned project, is jQuery’s Are You Sure? plugin, which also works great; see their demo page. Example usage:

    <script src="jquery.are-you-sure.js"></script>
    
    <script>
      $(function() {
        $('#myForm').areYouSure(
          {
            message: 'It looks like you have been editing something. '
                   + 'If you leave before saving, your changes will be lost.'
          }
        );
      });
      
    </script>
    

    Custom messages not supported everywhere

    Do note that since 2011 already, Firefox 4 didn’t support custom messages in this dialog. As of april 2016, Chrome 51 is being rolled out in which custom messages are also being removed.

    Some alternatives exist elsewhere on this site, but I think a dialog like this is clear enough:

    Do you want to leave this site?

    Changes you made may not be saved.

    Leave Stay

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have some pages that reference javascript files. The application exists locally in a
Lets suppose that I have some pages some.web/articles/details/5 some.web/users/info/bob some.web/foo/bar/7 that can call a
I have some pages on my site that are plain HTML pages, but I
I have some pages that I don't want users to be able to access
I have some pages on my public website that display charts generated by ASP.NET
I'm running tomcat and have some jsp pages that display a subset of a
I have an application that can be used without authentication on computers in public
I have a web application that once signed in, personalizes almost all pages. I
I have a web application that uses a couple of PDF forms to create
I have a form that I currently enumerate with some Javascript functionality and then

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.