gpt4 book ai didi

javascript - chrome.runtime.sendMessage 引发 "Uncaught TypeError: Cannot call method ' 未定义的 sendMessage'

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:06:19 25 4
gpt4 key购买 nike

我正在编写 google chrome 扩展程序,并尝试将信息从注入(inject)网页的一段代码发送到我的内容脚本。

根据 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";

然后将其注入(inject)网页,执行时,我得到:

Uncaught TypeError: Cannot call method 'sendMessage' of undefined

谁能帮我解决这个问题?

谢谢

最佳答案

Chrome 扩展中的 JavaScript 代码可以分为以下几组:

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

  • Content scripts (通过 list 文件或 chrome.tabs.executeScript )- Partial访问一些 chrome API
    拥有对页面 DOM 的完全访问权限。

  • 注入(inject)脚本(通过内容脚本中的 this method)- 完全访问页面中的所有属性。无法访问任何 chrome. API。*
    在实际页面执行,无法访问任何chrome.* API。**。

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

关于javascript - chrome.runtime.sendMessage 引发 "Uncaught TypeError: Cannot call method ' 未定义的 sendMessage',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21922005/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com