chrome.runtime.sendMessage引发"Uncaught TypeError:无法调用未定义的方法'sendMessage'"

Sté*_*ane 3 javascript jquery google-chrome google-chrome-extension

我正在编写一个谷歌浏览器扩展程序,并尝试从注入网页的一段代码中将信息发送到我的内容脚本.

根据http://developer.chrome.com/extensions/messaging#external-webpage,我应该使用类似的东西:

// The ID of the extension we want to talk to.
var editorExtensionId = "abcdefghijklmnoabcdefhijklmnoabc";

// Make a simple request:
chrome.runtime.sendMessage(editorExtensionId, {openUrlInEditor: url},
  function(response) {
    if (!response.success)
      handleError(url);
  });
Run Code Online (Sandbox Code Playgroud)

问题是,当我这样做时:

var script_code = "var msg = {message : 'plop'};\n";
script_code += "chrome.runtime.sendMessage('" + chrome.i18n.getMessage("@@extension_id") + "', msg, function(response) {\n";
script_code += "    console.log('response received');\n";
script_code += "});\n";
Run Code Online (Sandbox Code Playgroud)

然后将其注入网页,当它被执行时,我得到:

未捕获的TypeError:无法调用未定义的方法'sendMessage'

谁能帮我解决这个问题?

谢谢

小智 7

Chrome扩展程序中的javaScript代码可分为以下几组:

  • 扩展代码 - 完全访问所有允许的chrome.* API.
    这包括所有扩展页面(后台页面,弹出页面,选项页面等)

  • 内容脚本(通过清单文件或chrome.tabs.executeScript) - 部分访问某些chrome API
    完全访问页面的DOM.

  • 注入脚本(通过内容脚本中的此方法) - 对页面中所有属性的完全访问权限.无法访问任何chrome.*API.
    在实际页面上执行,无法访问任何chrome.* API.**.

在您的情况下,代码在实际页面上执行,不能调用chrome.runtime.*API.
也许,你可以试试window.postMessage().

  • 在此文档 https://developer.chrome.com/extensions/messaging#external-webpage 中,似乎可以访问“chrome.runtime”。但我收到错误“无法读取未定义的属性‘sendMessage’”。为什么? (4认同)