Detect browser lock or tab

Asked

Viewed 546 times

-2

Is there any Javascript/jQuery code between browsers to detect whether the browser or a browser tab is being closed?

1 answer

1


Use the event .unload(). https://api.jquery.com/unload/

Jquery < 3.0

$(window).unload(function() {
  alert("call");
  console.log("this will be triggered");
});

Jquery >= 1.7

$(window).on("unload", function(e) {
  alert("call");
  console.log("this will be triggered");
});

The Unload Event is sent to the window element when the user navigates away from the page. This could Mean one of Many Things. The user could have clicked on a link to Leave the page, or typed in a new URL in the address bar. The forward and back Buttons will Trigger the Event. Closing the browser window will cause the Event to be Triggered. Even a page Reload will first create an Unload Event.

The Unload event is sent to the window element when the user navigates off the page. This can mean one of many things. The user could have clicked on a link to exit the page or entered a new URL in the address bar. The back and forth buttons will trigger the event. Closing the browser window will trigger the event. Even a page reload will first create a download event.

google translator

  • Does this work on all browsers? "Blocked Alert('call') During Unload."

  • The compatibility of Jquery vc can be found here: https://jquery.com/browser-support/

  • Thank you. I will do a search, I am using the latest version of jQuery (3.3.1).

  • 1

    @Tfm see the documentation of the Unload event. This event occurs before the page is downloaded from memory, so the interface is no longer operational, i.e., functions like window.open, alert and confirm will not work.

  • 3

    You may want to use the event beforeunload.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.