Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome - Detect browser close or tab close

I am using following two listeners on my page when a user closes a tab or window in chrome, but they don't seem to work

chrome.tabs.onRemoved.addListener(function (integer tabId, object removeInfo) {alert("Haooooo")});

chrome.windows.onRemoved.addListener(function (integer windowId) {alert("Haooooo")});

But, the following function detects the window close or tab close, but gets triggered on refresh too. Has any one have a way to detect the browser/tab close only for Chrome. I am not looking for this to work in any other browser. Looking for a solution only in chrome

window.addEventListener("beforeunload", function (e) {          
          var confirmationMessage = "See you later" ;
          (e || window.event).returnValue = confirmationMessage;
          return confirmationMessage;
}
);
like image 493
RandomWanderer Avatar asked Jan 21 '16 19:01

RandomWanderer


People also ask

How do I detect if a browser window is closed or refreshed?

A tab or window closing in a browser can be detected by using the beforeunload event. This can be used to alert the user in case some data is unsaved on the page, or the user has mistakenly navigated away from the current page by closing the tab or the browser.

Does closing a tab close the browser?

Close tab with your keyboard's function keys The active tab closes, and your browser will make the first open tab the active one. If you have no other open tabs, it closes your browser.

What is the difference between browser refresh and close?

When we refresh the page (F5, or icon in browser), it will first trigger ONUNLOAD event. When we close the browser (X on right top icon),It will trigger ONUNLOAD event.

How do you handle browser tab close angular not close refresh?

You can use the onunload event handle to detect this.


1 Answers

Your syntax is invalid. It should be

chrome.tabs.onRemoved.addListener(function(tabid, removed) {
 alert("tab closed")
})

chrome.windows.onRemoved.addListener(function(windowid) {
 alert("window closed")
})

However, these apis will not work on normal webpages, only in extensions.

like image 79
Daniel Herr Avatar answered Sep 24 '22 18:09

Daniel Herr