<p>Is there any cross-browser JavaScript/jQuery code that can detect if the browser or browser tab is closed, but not as a result of clicking a link? </p>
For some reason, Webkit-based browsers do not follow the dialog box in the specification. The example below has a shutdown example that works almost across browsers.
window.addEventListener("beforeunload", function (e) {
var confirmationMessage = "\o/";
(e || window.event).returnValue = confirmationMessage; //Gecko + IE
return confirmationMessage; //Webkit, Safari, Chrome
});
This example is suitable for handling all browsers.
If I understand correctly, you want to know when a tab/window is effectively closed. Well, as far as I know, the only way to detect this in JavaScript is to use the onunload or onbeforeunload events.
Unfortunately (or fortunately?), these events also fire when you leave a website through a link or use your browser's back button. So this is the best answer I can give, I don't think you can natively detect a pure close in JavaScript. Please correct me if I understand wrong.
According to the MDN documentation:
For some reason, Webkit-based browsers do not follow the dialog box in the specification. The example below has a shutdown example that works almost across browsers.
This example is suitable for handling all browsers.
If I understand correctly, you want to know when a tab/window is effectively closed. Well, as far as I know, the only way to detect this in JavaScript is to use the onunload or onbeforeunload events.
Unfortunately (or fortunately?), these events also fire when you leave a website through a link or use your browser's back button. So this is the best answer I can give, I don't think you can natively detect a pure close in JavaScript. Please correct me if I understand wrong.