H3XED

Run Something When Chrome First Starts - Chrome Extension Development

Oct 24, 2014   Programming   Nick Vogt   Comments
Please note that this post is over a year old and may contain outdated information.
Since version 23 of Chrome, you can listen for the event onStartup, which will fire each time Chrome is started. If the user closes Chrome and quickly reopens it (before the chrome process has ended), it will still fire off this event when the Chrome window opens up.

This must be used inside the extension scope, such as on a background or event page. It cannot be used in a content script.

Add a listener to the onStartup event like so:

chrome.runtime.onStartup.addListener(callback function);
The callback function can be an anonymous function or a named function. Here are two examples:

// Anonymous function
chrome.runtime.onStartup.addListener(function() {
    // Do stuff here
});

// Named function
function doStuffOnStartup() {
    // Do stuff here
}
chrome.runtime.onStartup.addListener(doStuffOnStartup);


Chrome Running In Background


If Chrome is running always in the background, likely due to an extension requiring the background permission, then the user can close all of the Chrome windows without Chrome actually "closing". Then when they open up a new window, the onStartup event is not triggered.

To get around this, you can instead listen for window creation, and run your program when the first window is created, like so:

chrome.windows.onCreated.addListener(function() {
    chrome.windows.getAll(function(windows) {
        if (windows.length == 1) {
            // Do stuff here
        }
    });
});
Share This Post
Twitter

Comments (0)

Share This Post
Twitter
H3XED © Nick Vogt   RSS   Policies   Twitter