The BeforeUnloadEvent interface represents the event object for the beforeunload event, which is fired when the current window, contained document, and associated resources are about to be unloaded.
See the beforeunload event reference for detailed guidance on using this event.
When set to a truthy value, triggers a browser-controlled confirmation dialog asking users to confirm if they want to leave the page when they try to close or reload it. This is a legacy feature, and best practice is to trigger the dialog by invoking event.preventDefault() instead, as shown in the example.
Our JavaScript attaches an input event listener to the <input> element that listens for changes in the inputted value. When the value is updated to a non-empty value, a beforeunload event listener is attached to the Window object.
If the value becomes an empty string again (i.e. the value is deleted), the beforeunload event listener is removed again. It would be more efficient to just add the beforeunload listener once, and conditionally call preventDefault() based on the value of the target input. Best practice however is to add the listener when needed (i.e. when there is unsaved data that could be lost) and remove it again when it is not needed, for reasons outlined in the beforeunload event usage notes.
The beforeunload event handler function invokes preventDefault() to trigger the warning dialog when the user closes or navigates the tab.
When the <input> value is non-empty, if you try to close, navigate, or reload the page the browser displays the warning dialog. Try it out:
Note: The browser-generated confirmation dialog can also be triggered by setting the event.returnValue property to a truthy value on the beforeunload event object, or by returning a truthy value from the event handler function. However, these are legacy mechanisms, and best practice is to trigger the dialog by invoking event.preventDefault() as shown in the example above.