For a comprehensive guide on the beforeunload event and its implementation across different browsers, check out the Mozila Developer Network's API reference page. Utilize their suggested code snippet for optimal results.
Back in 2014:
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "\o/";
(e || window.event).returnValue = confirmationMessage; //Gecko + IE
return confirmationMessage; //Webkit, Safari, Chrome etc.
});
Fast forward to 2020:
window.addEventListener('beforeunload', (event) => {
// Implement standard cancellation of the event.
event.preventDefault();
// Set returnValue as required by Chrome.
event.returnValue = '';
});
Considering all options:
If ever faced with this scenario, relying on a trusted library for handling such events would be ideal. However, if manual intervention is necessary, covering all bases from previous versions can ensure maximum compatibility.
- Avoid setting custom message texts to maintain consistent user experience.
- Ensure proper event object assignment with
event = event || window.event
.
- Check for
preventDefault()
support before invoking it.
- Set
event.returnValue = ''
along with return ''
for complete coverage.