search

Home  >  Q&A  >  body text

Detect browser or tab closure

<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粉760675452P粉760675452483 days ago592

reply all(2)I'll reply

  • P粉958986070

    P粉9589860702023-08-01 10:50:07

    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.

    reply
    0
  • P粉821231319

    P粉8212313192023-08-01 00:40:43

    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.

    reply
    0
  • Cancelreply