Chrome Extension: Background page interval runs, b

2019-09-11 12:47发布

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.

3条回答
甜甜的少女心
2楼-- · 2019-09-11 13:16

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楼-- · 2019-09-11 13:23

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

查看更多
放我归山
4楼-- · 2019-09-11 13:28

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);
查看更多
登录 后发表回答