10

我是 chrome 扩展的新手,似乎无法弄清楚背景概念是如何工作的。我正在构建一个计数器扩展,即使用户关闭扩展(但不是浏览器),它也会继续计数,并且想做一个简单的测试,看看我是否能弄清楚如何使用背景文件。下面是我尝试创建一个功能,该功能在用户每次单击选项卡(在我的扩展程序之外)时激活,并且当他们单击 5 个选项卡时,会触发警报。我无法弄清楚为什么这不起作用。

背景.js:

var counter = 0;
chrome.browserAction.onClicked.addListener(function(tab){
  counter++;
  if (counter == 5) {
    alert("Hi");
  }
});

清单.json:

 {
  "name": "Hello World!",
  "description": "My first packaged app.",
  "version": "0.1",
  "permissions": ["tabs", "http://*/*"],
  "manifest_version":2,
  "content_scripts": [ {
    "js": [ "jquery-1.9.1.js", "myscript.js" ],
    "matches": [ "http://*/*", "https://*/*"]
  }],
  "background": {
    "scripts": [
       "background.js"
    ]
  },
  "browser_action": {
    "default_title": "10,000 Hours",
    "default_icon": "icon16.png",
    "default_popup": "index.html"
  },
  "icons": {
    "16": "icon16.png",
    "48": "icon48.png",
    "128": "icon128.png"
  }
}
4

1 回答 1

12

它使用以下代码为我工作。

清单.json

{
    "name": "Popping Alert",
    "description": "http://stackoverflow.com/questions/15194198/background-js-not-working-chrome-extension",
    "background": {
        "scripts": [
            "background.js"
        ]
    },
    "version": "1",
    "manifest_version": 2,
    "browser_action": {
        "default_title": "Click Me"
    }
}

背景.js

var counter = 0;
chrome.browserAction.onClicked.addListener(function (tab) {
    counter++;
    if (counter == 5) {
        alert("Hey !!! You have clicked five times");
    }
});

如果这不起作用,您能否分享您的相关代码或清楚地说明您的问题?

于 2013-03-04T05:53:26.720 回答