Google chrome extension chrome.extension.onMessage.addListener无法读取属性';onMessage';未定义的

Google chrome extension chrome.extension.onMessage.addListener无法读取属性';onMessage';未定义的,google-chrome-extension,Google Chrome Extension,在background.html中: chrome.tabs.query({active:true, currentWindow:true},function(tabs){ chrome.tabs.sendMessage(tabs[0].id,"target.js"); }); 在content.js中: chrome.extension.onMessage.addListener(function(msg,sender,sendResponse){ if (msg == "targe

background.html
中:

chrome.tabs.query({active:true, currentWindow:true},function(tabs){
  chrome.tabs.sendMessage(tabs[0].id,"target.js");
});
content.js
中:

chrome.extension.onMessage.addListener(function(msg,sender,sendResponse){
  if (msg == "target.js"){
    extensionID = sender.id;
  }
});
然而,它不起作用

Uncaught TypeError: Cannot read property 'onMessage' of undefined 

如何使其正确?

看起来您正试图对当前选项卡执行一些操作。你确定你需要留言吗?我假设background.html是扩展的背景页面,content.js是内容脚本。现在我跳过background.html页面,只需为我的背景页面运行一个javascript文件。我的manifest.json页面看起来像这样

  "background": {
     "scripts": [ "js/background.js"]
  },
在该页面中,我将消息侦听器添加到我的后台页面,因为这是我知道的与background.js文件交互的唯一方式。但是,在您的情况下,执行操作的是后台页面,因此您可以使用chrome.tab方法直接修改当前选项卡。您可以尝试使用executeScript而不是onMessage,其中InjectDetails是javascript或任何您想要执行的内容

chrome.tabs.query({active:true, currentWindow:true},function(tabs){
         chrome.tabs.executeScript(tabs[0].id, InjectDetails);
});
查看更多信息。

您说过“content.js是一个内容脚本,它由另一个内容脚本注入当前选项卡。”

这就是你的问题所在。注入的脚本在页面上下文中执行(就像它们是由页面本身创建的一样),因此它们无法访问任何Chrome扩展API

您可以使用自定义事件或
postMessage
在页面和内容脚本之间进行通信,而内容脚本又与后台页面进行通信

例如,请参见以下基本示例:

// Injected script script
addEventListener('message', function(event) {
    if (event.data && event.data.extensionMessage) {
        alert(event.data.extensionMessage);
    }
});
// Content script which injects the script:
chrome.extension.onMessage.addListener(function(message) {
    postMessage({extensionMessage: message}, '*');
});

我认为您希望使用
content.js
作为真正的内容脚本,而不是注入脚本。如果您想了解注入脚本和内容脚本之间的区别,请参阅。

您使用的是Chrome 19还是更低版本?
content.js
是一个内容脚本吗?我正在使用chrome 21。content.js是一个内容脚本,它被另一个内容脚本注入到当前选项卡。事实上,我只想在content.js中获取扩展名的id。但是content.js中似乎不允许使用chromeAPI。因此我尝试了这种方法,但失败了。。。。。content.js是一个内容脚本,它被另一个内容脚本注入到当前选项卡中,我不知道这是否重要……非常感谢,我稍后会尝试。我的扩展中有两个脚本。一个是content.js,一个是target.js(这是一个真正的content.js)。是否注入content.js取决于target.js,我需要在content.js中获取extensionID,所以我想在background.html和content.js之间交换消息。您所说的启发我使用localStorage解决了这个问题……非常感谢~~