Search code examples
jquerygoogle-chrome-extensiongetjson

Chrome Extension - Execute code when Chrome Starts


I'm working on a Chrome Extension, and I'm researching how to execute code when chrome starts.

I have these files:

script.js
index.html
manifest.json

And in script.js I have:

$(document).ready(function() {
    $.getJSON("https://api.twitch.tv/kraken/streams/"+"NameOfStreamer",function(c) {
        if (c.stream == null) {
            ...
        } else {
            ...
        }
    });
});

I would like to execute this code not when the HTML is done rendering but when Chrome starts in the first place, then rerun every minute.

It would be the same idea as $(document).ready(), but executed when Chrome starts.


Solution

  • Please start by reading the Architecture Overview. It's not a long text, but extremely important.

    A popup only exists as long as it is open; there is no code to run when it's not.

    A background page is the solution: it's an invisible page that is created as soon as Chrome starts and continues running throughout the lifetime of Chrome.


    Implementation:

    In your manifest, declare your background scripts (in the order of loading):

    "background" : {
      "scripts": ["jquery.js", "background.js"]
    },
    

    The code will be run as soon as Chrome starts. No $(document).ready wrapper needed:

    $.getJSON("https://api.twitch.tv/kraken/streams/"+"NameOfStreamer", function(c) {
      /* ... */
    });
    

    If you need it repeated, you can use chrome.alarms API or simply DOM intervals:

    getData();
    setInterval(getData, 60000); // Once every minute
    
    function getData() {
      $.getJSON("https://api.twitch.tv/kraken/streams/"+"NameOfStreamer", function(c) {
        /* ... */
      });
    }
    

    That solves the problem of getting the updated data. But the background page is invisible. If you want to show the data, you can use the browserAction popup.

    This way, you separate your extension into the part that handles the data (background) and a popup that displays it.

    You will have to request the data from the background somehow; how to do this is too broad for this question, but you can use Messaging API or directly access the background page with chrome.runtime.getBackgroundPage(). You could also store the data in chrome.storage, accessible from the popup. This is probably not an exhaustive list.

    Alternatively, depending on your needs, you might want to look into notifications.