我正在撰写Google Chrome扩展程序,并尝试将注入网页的一段代码中的信息发送到我的内容脚本。
根据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);
});
问题是,当我这样做时:
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";
然后将其注入网页,当它被执行时,我得到:
未捕获的TypeError:无法调用未定义的方法'sendMessage'
有人可以帮我解决这个问题吗?
由于
答案 0 :(得分:6)
Chrome扩展程序中的javaScript代码可分为以下几组:
扩展程序代码 - 对所有允许的chrome.* API的完全访问权限。
这包括所有扩展页面(背景页面,弹出页面,选项页面等)
Content scripts(通过清单文件或chrome.tabs.executeScript) - Partial访问某些Chrome API
完全访问页面的DOM。
注入的脚本(通过内容脚本中的this method) - 对页面中所有属性的完全访问权限。无法访问任何chrome。* API。
在实际页面上执行,无法访问任何chrome.* API。**。
在您的情况下,代码在实际页面上执行,无法调用chrome.runtime。* API 也许,你可以尝试window.postMessage()。
答案 1 :(得分:-2)
实际上,我包含了manifest.json文件的错误版本。
我的不好,这是您指定要将消息传递API公开给某些网站的地方。
问题解决了。