Onbeforeunload is subject of one of bigest missunderstanding in the webdevelopers world :D
1) It refuses to call all blocking native functions (alert, prompt, confirm). It is obvious from User perspective.
2) it (according to MDN) should be registered by "addEventListener" (MDN)
3) It is fired only if there was ANY interaction of the user with the site. Without ANY interaction (even one click anywhere) event onbeforeunload won't be fired.
4) The aim of this event IS eg. secretly saving data left in forms (or else) on behalf of user (or logging user behavior etc.). It is NOT for blocking refreshing the site !
Thus there is no way (because it would be for nothing) to show personalised information.
The only sens is to hide the prompt window while reloading with prior saveing data.
5) If you want to hide the prompt window just NOT set any value for the event.returnValue field.
This example unload site (writing on console text "UNLOAD:1") without window prompt during refresh.
window.addEventListener("beforeunload", function(event) {
console.log("UNLOAD:1");
//event.preventDefault();
//event.returnValue = null; //"Any text"; //true; //false;
//return null; //"Any text"; //true; //false;
});
This example unload site (writing on console text "UNLOAD:1") WITH window prompt during refresh.
window.addEventListener("beforeunload", function(event) {
console.log("UNLOAD:1");
//event.preventDefault();
event.returnValue = null; //"Any text"; //true; //false;
//return null; //"Any text"; //true; //false;
});
You can use any kind of value to event.returnValue (as listed on the right). It is just coding style matter.
Both event.preventDefault nor return has no influence on this event (so in your code you can omit those commented lines).
Tested on Chrome, Edge, Firefox, Opera (verified on 23.09.2019). Hope it helps.
[EDIT:]
To avoid reloading mobile application by accidentally swipe/drag of the screen (eg. google maps, images and any other stable content) this css trick can be usefull:
body {
overscroll-behavior-y: contain !important;
}
The application will be safe against reloading.
It is woth to consider to give to user another possibilty (eg. some button) to reload if needed.