javascript Background.js 不工作 Chrome 扩展

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15194198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 23:49:45  来源:igfitidea点击:

Background.js not working Chrome Extension

javascriptgoogle-chromegoogle-chrome-extension

提问by user1987920

I'm new to chrome extensions and cannot seem to figure out how the background concept works. I am building a counter extension that keeps counting even when the user closes the extension (but not the browser) and wanted to do a simple test to see if I could figure out how to use the background file. Below is my attempt to create a function that activates everytime a user clicks on a tab (outside of my extension) and when they click on 5 tabs, the alert hits. I cannot figure out why this doesn't work.

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

background.js:

背景.js:

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

manifest.json:

清单.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"
  }
}

回答by Sudarshan

It is working for me with following code.

它使用以下代码对我来说有效。

manifest.json

清单文件.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"
    }
}

background.js

背景.js

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

Can you share your related code or put your problem statement clearly if this does not work?

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