Search code examples
jquerycross-browseronchangedom-eventsback-button

How do I make the browser back button trigger an input's change event?


I'm trying to detect changes to input fields to warn users of unsaved changes on a form. I'm using the onchange event on fields to record that the form changed. I'm then using the beforeunload window event to stop the user from leaving the page if a save is needed. The problem is that the back button on all major browsers does let the active input fire the change event. How do I get around this problem?

Below are the test files I'm using. I want the alert to fire when the user edits the input field and then immediately clicks back. Editing the text and then clicking on the body will trigger change but that along is not enough.

starteditor.html

<!doctype html>
<html>
<head>
</head>
<body>
    <a href="editor.html">Click me</a>
</body>
</html>

editor.html

<!doctype html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script> 
    <script>
        $(document).ready(function(){
            $("form").delegate("input", "change", function () { alert("I changed") });
        });
    </script>
</head>
<body>
    Edit text then click the browsers back button.
    <form>
        <input type="text" />
    </form>
</body>
</html>

Solution

  • Short answer: you don't.

    The back button belongs to the user and is outside the purvey of the page. The closest you'll get is the window.unload event. But the window won't know whether the user has closed the window, hit the back button, hit the F5 to refload the page, typed a new URL into the URL entry field, opened a bookmark or told the browser to shut down or any other way you might dismiss a page. Further, you can't cancel the unload event: it's provided so that the page can cleanly shut down.

    From the spec at http://www.w3.org/TR/DOM-Level-2-Events/events.html, section 1.6.5 (HTML event types):

    unload
    The unload event occurs when the DOM implementation removes a document from a window or frame. This event is valid for BODY and FRAMESET elements.
    • Bubbles: No
    • Cancelable: No
    • Context Info: None