Warn of Unsaved Changes in JavaScript

- 1 minute read

Have you ever used a web page where you saw a popup warning you about leaving behind unsaved changes before closing the tab?

This is especially common for preventing lost progress on things like forms and online editors.

It turns out that we can easily add the same functionality to our app with just a few lines of JavaScript:

const warning = (e) => {
    // The first two lines ensure compatibility with older browsers:
    e = e || window.event;
    e && (e.returnValue = `Are you sure?`);
    // For most browsers, just the following line is sufficient:
    return `Are you sure?`;

window.addEventListener(`beforeunload`, warning);

You can test this out by reloading a page where the warning function has been tied to the window’s “beforeunload” event listener.

Link to this section Conclusion

I noticed many similar snippets online did not support certain older browsers, such as early versions of Internet Explorer and Firefox.

Anyway, I hope you found this useful!