Does onbeforeunload event trigger for popup.html in a google chrome extension?

Viewed 7072

I'm writing a google chrome extension with a popup and a background page. The popup subscribes to certain events that the background generates, and I would like to unsubscribe from those events when the popup goes away. However, I don't see either of onbeforeunload or onunload events being generated from the popup. Are these events fired? If not, any ideas on how to capture popup close?

4 Answers

If you've switched to using event pages instead of background pages in your extension, the recommended way of getting access to it is calling chrome.runtime.getBackgroundPage() with a function that gets called back with the background page reference.

However, if you try to get the background page in an onbeforeunload handler, like this:

document.addEventListener("beforeunload", function() {
    chrome.runtime.getBackgroundPage(function(backgroundPage) {
        backgroundPage.log("unloading");
    });
});

The callback doesn't seem to fire before the page unloads, so that log() call is never made.

In a comment above, Pauan suggested using chrome.extension.getBackgroundPage() to get the page. The only way I could get that to work was not to create the handler with addEventListener(). Instead I had to go old school and set the handler directly on window:

window.onbeforeunload = function() {
    chrome.extension.getBackgroundPage().log("unloading");
};

That finally got through to the background page.

Use the messaging APIs to set up a Port between the popup and background page. You then should get a onDisconnect event in the background page when the popup goes away.

// 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");
    });
  }
});
Related