I came across a lot of similar questions on stack overflow, but the issue is that most of them are old (as in answered near about 3 to 4 years ago).
PROBLEM
I want to execute a function when the tab is closed (I want to use vanilla java-script) . I've tried doing the following:
// No.1 -> THROWS AN ERROR *Blocked alert('hello') before onunload*
window.onunload = function() {
alert('hello');
}
// No.2 -> THROWS AN ERROR *Blocked alert('hello') before onunload*
window.onbeforeunload = function(){
alert('hello')
};
Way no.3 shown below works as it throws a dialog before leaving or reloading, but the issue is that it runs a function when we click "X" and try to close the tab but when the dialog appears which has two buttons leave and cancel.
window.addEventListener('beforeunload', (event) => {
event.preventDefault();
event.returnValue = '';
bye();
});
function bye() {
console.log('leaving');
}
The way presented above runs the function when we click on "X" but logically the function should run after we click on leave. Refer to the Screenshot below :
I need the function to execute after we click on leave or is there any other way to achieve this ?
PS: I am running vue-js but need plain JS solution