Naga K
Naga K

Reputation: 743

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;
}
);

Upvotes: 18

Views: 18697

Answers (1)

Daniel Herr
Daniel Herr

Reputation: 20478

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.

Upvotes: 26

Related Questions