Prompting a user to confirm navigation away from a page using the "beforeunload" event in javascript

Submitted by Charles on Sun, 08/19/2018 - 13:43

To brush up on, and solidify my javascript knowledge, I'm currently going through the book "Eloquent Javascript", and came across the brief mention of "load" and "unload" events. I'm well aware of and use the "load" event all the time, but I haven't actually needed to use the "unload" event in any custom js code of mine before, so while the book doesn't really go into any detail I looked at the MDN's "beforeunload" documentation for some more info. 

Before a webpage is closed or navigated away from, the "beforeunload" event is fired, allowing one to check that the user hasn't got any unsaved work that they may want to save before moving away.

The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point. If a string is assigned to the returnValue Event property, a dialog appears asking the user for confirmation to leave the page (see example below). Some browsers display the returned string in the dialog box, but others display their own message. If no value is provided, the event is processed silently.

From the docs (and my testing in Chrome 68 and Firefox 61) it appears that one needs to return a string for it to work in Chromium based browsers. The string itself doesn't actually show in either Firefox or Chrome, just the default browser modal asking for confirmation to stay or leave. Here's the code:

window.addEventListener("beforeunload", function (event) {
// Most browsers.
// Chrome/Chromium based browsers still need this one.
event.returnValue = "\o/";

Default browser modal