Reputation: 4902
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.
Upvotes: 48
Views: 26347
Reputation: 29
This is the solution I used for manifest V3:
Set up a connection in your popup's JavaScript file
chrome.runtime.connect();
In background.js, use onConnect
to listen for the event
chrome.runtime.onConnect.addListener(port => {
port.onDisconnect.addListener(()=>{
//Your event will be fired in here
})
})
Upvotes: 2
Reputation: 19
Try to use the visibilitychange event on the document object. It works fine for me:
document.addEventListener('visibilitychange', MyFunction, false);
Upvotes: 1
Reputation: 480
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);
});
Upvotes: 3
Reputation: 2475
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.
Upvotes: 19
Reputation: 28751
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.
Upvotes: 4
Reputation: 2052
Probably a hacky way, but in the popup page you can listen to
window.onblur = function(){}
and send a message to active tab.
Upvotes: 10
Reputation: 49150
Finally found the solution. Put below code in background.js
/eventPage.js
:
chrome.windows.onFocusChanged.addListener(function(window) {
//handle close event
});
Upvotes: 0
Reputation: 4162
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.
Upvotes: 35