ebi
ebi

Reputation: 4902

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.

Upvotes: 48

Views: 26347

Answers (8)

zinzin
zinzin

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

Murillo
Murillo

Reputation: 19

Try to use the visibilitychange event on the document object. It works fine for me:

document.addEventListener('visibilitychange', MyFunction, false);

Upvotes: 1

Petr L.
Petr L.

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

gignu
gignu

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

user7610
user7610

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

nxtwrld
nxtwrld

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

GorvGoyl
GorvGoyl

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

Related Questions