gpt4 book ai didi

google-chrome-extension - 端口错误: Could not establish connection. 接收端不存在。含 Chrome

转载 作者:行者123 更新时间:2023-12-03 06:00:22 25 4
gpt4 key购买 nike

我正在 Chrome 中开发扩展程序,但出现了问题。在我的 inject.js 中,我发出如下请求:

chrome.extension.sendRequest({command:'skip'},callback)

在我的“background.js”中,我只需添加一个请求监听器,例如:

chrome.extension.onrequest.addListener(function(req,sender,res){console.log("procession"})

但是有一个错误:

端口错误:无法建立连接。接收端不存在

这似乎是 Chrome 中的一个错误?PS:
我的manifest.json的一部分

"background": {
"scripts": ["background.js"]
},
"content_scripts": [
{
"matches": ["< all_urls >"],
"js": ["inject.js"]
}
],

我使用的是 Chromium 17,我尝试重新加载扩展程序,重新打开浏览器...什么也没发生
有人有一些想法吗?

最佳答案

这里的一些其他答案有很好的调试建议或拼图的一小部分,但是如果您想像我一样注入(inject)(第3方)网页,那么这里没有列出正确的答案组件。

共有 4 个步骤:

  • 外部后台监听器,
  • 前台消息发送者,
  • 为消息发送者注入(inject)扩展 ID
  • 以及 list 中将所有内容链接在一起的规则。

下面的示例应该是您所需的一切,允许您注入(inject)一个 js,将消息从 google.com 上的任何页面发送到您自己的扩展程序

首先,您需要在 ma​​nifest.json 中添加消息规则,即 described here :

"externally_connectable": {
"matches": ["*://*.google.com/*"]
}

然后在您的后台脚本或页面中,您需要一个外部监听器(不是常规的 chrome.runtime.onMessage。 msot 答案中已提到的 addListener),这是 described here :

chrome.runtime.onMessageExternal.addListener( (request, sender, sendResponse) => {
console.log("Received message from " + sender + ": ", request);
sendResponse({ received: true }); //respond however you like
});

一旦有了这些部分,您就可以像平常一样使用消息发送者,但将扩展程序 ID 作为第一个参数:

chrome.runtime.sendMessage(myExtId, { /* whatever you want to send goes here */ },
response => {
/* handle the response from background here */
}
);

如果您不知道如何获取我用作第一个参数的外部 ID,您可以注入(inject)您的扩展 ID,如下所示。这是必需的,因为 chrome.runtime.id@@extension_id 都无法在注入(inject)的脚本中工作:

//create a script tag to inject, then set a variable with the id in that script
let idScript = document.createElement("script");
idScript.setAttribute("type", "application/javascript");
idScript.textContent = 'var myExtId = "' + chrome.runtime.id +'";';
let parent = ( document.head || document.documentElement );
parent.insertBefore( idScript, parent.firstChild );

//inject and run your other script here

idScript.remove(); //then cleanup

因为我们将其设置为var,所以其他脚本现在可以直接访问该值

关于google-chrome-extension - 端口错误: Could not establish connection. 接收端不存在。含 Chrome ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9106519/

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