hucuhy
hucuhy

Reputation: 829

How to start event with "background page" when chrome open and close

I don't know how to start event with "background page" when chrome open and close.

For instance, alert("open") when chrome open and alert("close") when chrome close.

Please help me.

Upvotes: 5

Views: 2650

Answers (1)

Rob W
Rob W

Reputation: 349232

Without any context, I'll just give a general overview on the possibilities.
Caution: Do not rely on "close" events! If you need to synchronize variables, use window.setInterval or chrome.alarms to periodically save variables. When Chrome is closed, your extension will usually be unloaded as well. You can't perform any asynchronous tasks, and even synchronous tasks could fail if it takes too long (issue 227335).

Common cases

  • Startup (fine-grained):
  • Startup (all-in-one, only for background pages, not for event pages):
    • Put the code directly in background.js. Whenever background.js is run, assume that either Chrome is loaded, or the extension has just been installed/updated.
  • Chrome is being closed: Use the window.onunload event.

Detect Chrome Open / Close

Counting windows makes most sense if your extension has the background permission. Without this permission, your extension will be unloaded when the last window of Chrome is closed. With the background permission, your extension will stay around even when all Chrome windows are closed. Note: Do not add the background permission unless your extension really needs it; wanting to monitor whether Chrome is "open" or "closed" is not a good reason!

To detect when a window has been opened, use the chrome.windows.onCreated event.
To detect when a window has been closed, use the chrome.windows.onRemoved event.

In order to know whether Chrome is being opened or closed, simply count the number of windows. For example:

// background.js
var windowCount = 0;
chrome.windows.getAll({}, function(windows) {
    windowCount = windows.length;
    chrome.windows.onCreated.addListener(function() {
        ++windowCount;
        checkWindowCount();
    });
    chrome.windows.addListener(function() {
        if (--windowCount === 0) {
            alert('Closed!');
        }
    });
    checkWindowCount();
});

// Called when the number of windows have been incremented
function checkWindowCount() {
    if (windowCount === 1) {
        alert('Opened!');
    }
}

Upvotes: 7

Related Questions