-->

Chrome Extension: Background page interval runs, b

2019-09-11 12:59发布

问题:

I am creating a chrome extension that has background, which runs every second and updates chrome.storage... and it is called artistSetter.js. Here it is:

chrome.storage.local.get(function(items){
    $.each($('#supplySong > a > span.sidebar-heading'), function(){
        if ($(this).css('background-color') == 'rgb(22, 156, 217)'){
            chrome.storage.local.set({"currentArtist": $(this)[0].innerText});
        }
    });
});

Background page is this:

setInterval(function () {
    chrome.tabs.executeScript(null, {file: 'js/artistSetter.js'});
}, 1000);

The error is this:

Error in response to storage.get: ReferenceError: $ is not defined

The thing is that this is working after page refreshes. I understand, that this works because I jQuery.js starts running. But when I click Reload button, it stops working and I start getting the error every second. Again, after refreshing, it works. Because jQuery.js starts working.

How can I fix this? Really couldn't find a way.

回答1:

Add the required plugin before running artistSetter.js, e.g.:

setInterval(function () {
    chrome.tabs.executeScript(null, {file: 'jquery.js'});
    chrome.tabs.executeScript(null, {file: 'js/artistSetter.js'});
}, 1000);


回答2:

Why not put the setInterval logic to content scripts, keep artistSetter.js only and remove background page?

Manifest.json

"content_scripts": [
    {
      "matches": [
        "*://*/*"
      ],
      "js": [
        "jquery.js",
        "artistSetter.js"
      ],
      "run_at": "document_end",
      "all_frames": true
    }
  ],

artistSetter.js

setInterval(function () {
    chrome.storage.local.get(function(items){
        $.each($('#supplySong > a > span.sidebar-heading'), function(){
            if ($(this).css('background-color') == 'rgb(22, 156, 217)'){
                chrome.storage.local.set({"currentArtist": $(this)[0].innerText});
            }
        });
    });
}, 1000);


回答3:

As other solution, You can concatenate the two script files to one file with some tool (ex. grunt-contrib-concat).