chrome.runtime.onInstalled未定义

Mic*_*ter 3 javascript google-chrome google-chrome-extension

我要在安装扩展程序后启动这些选项。这是我在这种情况下尝试使用的许多解决方案。

我的问题chrome.runtime.onInstalled是未定义。这是我的源代码:

background.js

if(typeof chrome.runtime.onInstalled  !== 'undefined')
{
    chrome.runtime.onInstalled.addListener(function (details)
    {
        //if(details.reason == 'update') window.open(chrome.extension.getURL('options.html'));
        if(details.reason == 'install') window.open(chrome.extension.getURL('options.html'));
    });
}
Run Code Online (Sandbox Code Playgroud)

我的manifest.json

{
  "name": "Context Menu 2.0 for Google Translate™",
  "short_name": "Translate",
  "version": "1.0.0.4",
  "manifest_version": 2,
  "description": "Creates a context menu option to translate selected texts to a specified language",
  "icons": {
    "16": "trans_16.png",
    "64": "trans_64.png",
    "128": "trans_128.png"
  },
  "content_scripts": [
    {
      "matches":
      [
          "http://*/*", "https://*/*"
      ],
      "js": ["background.js"]
    }
  ], 
  "options_page": "options.html",
  "background": {
    "scripts": ["background.js"]
  },
  "permissions":[
    "http://*/*", "https://*/*",
    "storage","contextMenus"
  ]
}
Run Code Online (Sandbox Code Playgroud)

我是否在清单中缺少某些内容,或者为什么未定义函数?我必须将支票包装起来才能使附加组件正常工作。否则,我总是会收到一个错误,该错误会停止执行脚本。

Xan*_*Xan 5

由于某种原因,您正在尝试使用与后台脚本和内容脚本相同的脚本。绝对不要这样做,因为这很容易混淆,原因如下。我敢打赌您会在内容脚本中看到此错误。

内容脚本只能非常有限地访问Chrome API;特别是,此事件对他们不可用。也没有任何意义,因为扩展初始化时内容脚本还不存在