Is there an event for when a Chrome Extension popup is closed?
I've already tried window.unload, window.beforeunload, etc. I'm looking for a way to notify my background page once the popup is closed.
Solution 1:
You can try this. Connect to your background page with chrome.runtime.connect (or chrome.extension.connect
before Chrome 26) and port.onDisconnect
will be fired in your background page when the popup is closed.
Solution 2:
Probably a hacky way, but in the popup page you can listen to
window.onblur = function(){}
and send a message to active tab.
Solution 3:
It's as simple as that:
// popup.js
chrome.runtime.connect({ name: "popup" });
// background.js
chrome.runtime.onConnect.addListener(function(port) {
if (port.name === "popup") {
port.onDisconnect.addListener(function() {
console.log("popup has been closed")
});
}
});
Note that there are some edge cases where this method doesn't work. E.g. when having the popup open and then switching tabs by using a keyboard shortcut such as ctrl + t for example.
Solution 4:
There is currently no way to figure out when the browser action popup was
closed as window.unonload
is triggered immediately when the popup finished
loading, not when it's closed. There is a bug crbug.com/31262 for this.
Three work arounds available are well described here. They include the port.onDisconnect
trick and periodically polling chrome.extension.getViews()
from either the popup or a background page.
Solution 5:
I'm surprised noone mentioned this (I've tested it on Firefox Nightly and it works there):
window.addEventListener("pagehide", function(event) {
console.log(event);
});