marijnh / Eloquent-JavaScript

The sources for the Eloquent JavaScript book
https://eloquentjavascript.net
3.02k stars 796 forks source link

3rd Edition, Ch. 15, Handling Events, Load Event, beforeunload #489

Closed thaxy closed 5 years ago

thaxy commented 5 years ago

First of all thanks for this awesome book. I am not sure if I spotted a passage worth to update/review or if it is just me not understanding the content. But I am having problem to reproduce your described behavior.

3rd Edition, Page 255 Chapter 15: Handling Events Load Event

When a page is closed or navigated away from (for example, by following a link), a "beforeunload" event fires. The main use of this event is to prevent the user from accidentally losing work by closing a document. Preventing the page from unloading is not, as you might expect, done with the preventDefault method. Instead, it is done by returning a non-null value from the handler. When you do that, the browser will show the user a dialog asking if they are sure they want to leave the page. This mechanism ensures that a user is always able to leave, even on malicious pages that would prefer to keep them there forever and force them to look at dodgy weight-loss ads.

This doesn't work with the most recent versions of the Firefox and Chrome browser:

window.addEventListener('beforeunload', () => "non null return value");

While the following handler works and is contradicting because it calls the method preventDefault and returns undefined:

window.addEventListener('beforeunload', e => {
  // Cancel the event
  e.preventDefault();
  // Chrome requires returnValue to be set
  e.returnValue = '';
});

You can find the same snippet of the code above in the official MDN docs.

marijnh commented 5 years ago

Thanks for spotting that. When you do window.onbeforeunload = () => "stop", that apparently still works, but when using addEventListener, you do need to call preventDefault and (on Chrome) set returnValue. I've updated the text and added an errata entry in attached patch.