I have an HTML tag with a target attribute. The issue is that I want to prevent the user leaving my site this way without saving his changes.
I tried
window.onbeforeunload = function(){
myfun();
return 'Are you sure you want to leave?';
};
Also changed my code to:
window.addEventListener('onbeforeunload', (e) => {
e.preventDefault();
console.log('Inside event')
})
But that didn't do it...
The return 'string' method does not work reliably everywhere. Most, if not all Web browsers won't show a custom message. And you also need to call preventDefault on the event:
window.onbeforeunload = (event) => {
myfun();
event.preventDefault();
return 'Are you sure you want to leave?';
};
EDIT This will not work using alert, confirm or prompt because it will override the browser's default message before displayed. You can do anything else though:
window.onbeforeunload = function(e){
console.log('Leaving...');
e.preventDefault();
};