0

我正在创建一个具有背景的 chrome 扩展,它每秒运行一次并更新 chrome.storage...,它被称为artistSetter.js. 这里是:

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});
        }
    });
});

背景页面是这样的:

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

错误是这样的:

响应 storage.get 时出错:ReferenceError: $ is not defined

问题是这在页面刷新后起作用。我明白,这行得通,因为我jQuery.js开始跑步。但是当我单击Reload按钮时,它停止工作,并且我开始每秒都收到错误。再次,刷新后,它的工作原理。因为 jQuery.js 开始工作了。

我怎样才能解决这个问题?实在是找不到办法了。

4

3 回答 3

1

在运行之前添加所需的插件artistSetter.js,例如:

setInterval(function () {
    chrome.tabs.executeScript(null, {file: 'jquery.js'});
    chrome.tabs.executeScript(null, {file: 'js/artistSetter.js'});
}, 1000);
于 2016-02-24T00:18:23.520 回答
1

为什么不将setInterval逻辑放到内容脚本中,只保留 ArtistSetter.js 并删除背景页面?

清单.json

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

艺术家Setter.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);
于 2016-02-24T00:56:01.593 回答
0

作为其他解决方案,您可以使用某些工具(例如grunt-contrib-concat)将两个脚本文件连接到一个文件。

于 2016-02-24T04:11:55.020 回答