The shortest solution for the year 2020 (for those happy people who don't need to support IE)
Tested in Chrome, Firefox, Safari.
function onBeforeUnload(e) {
if (thereAreUnsavedChanges()) {
e.preventDefault();
e.returnValue = '';
return;
}
delete e['returnValue'];
}
window.addEventListener('beforeunload', onBeforeUnload);
Actually no one modern browser (Chrome, Firefox, Safari) displays the "return value" as a question to user. Instead they show their own confirmation text (it depends on browser). But we still need to return some (even empty) string to trigger that confirmation on Chrome.