Chrome Extension: Background page interval runs, but sees no jQuery plugin

北慕城南 提交于 2019-12-12 03:57:22

问题


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).



来源:https://stackoverflow.com/questions/35590830/chrome-extension-background-page-interval-runs-but-sees-no-jquery-plugin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!