Detect browser or tab closure
P粉760675452
P粉760675452 2023-07-31 13:55:00
0
2
613
<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>
P粉760675452
P粉760675452

reply all(2)
P粉958986070

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.


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.

P粉821231319

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template