如何解决弹出内容脚本:无法建立连接接收端不存在
我想从弹出窗口向内容脚本发送一条消息,并在收到此端的响应后记录一个对象,但出现以下错误:无法建立连接。接收端不存在。
除了下面的代码之外,我还尝试了此链接 (https://www.youtube.com/watch?v=jooc7xMkz2E) 上建议的解决方法,方法是使用长期连接实现弹出窗口和内容脚本之间的通信,并在加载时向浏览器添加事件侦听器窗口,但它也不起作用。
实现了一个类似的功能,用于将消息发送到后台,但没有将选项卡作为参数传递,并且它将响应从后台记录到弹出窗口而不是从内容脚本到弹出窗口,当我尝试时出现错误从弹出窗口向内容脚本发送消息并记录相应的响应。
以下是主要的项目文件。
Popup.ts:
ngOnInit(): void {
...
this.sendMessagetoContentScript();
}
sendMessagetoContentScript() {
chrome.tabs.query({currentwindow: true,active: true},function (tabs){
var activeTab = tabs[0];
chrome.tabs.sendMessage(activeTab.id,{ command: 'HelloFromPopup1' },(response) => {
var parsed_res = JSON.parse(response);
console.log("content-script: " + parsed_res);
});
});
}
content_script.ts:
chrome.runtime.onMessage.addListener(
function(msg,sender,sendResponse) {
if (msg.command == "HelloFromPopup1") {
var personal_data = {
firstname: "Max",lastname: "Hennigan",role: "role",location: "United Kingdom"
};
sendResponse(JSON.stringify(personal_data));
}
}
);
Manifest.json:
{
"name": "Extension name","version": "1.0","description": "Desc","manifest_version": 2,"permissions": [
"activeTab","webNavigation","tabs","storage","http://*/","https://*/"
],"background": {
"persistent": true,"scripts": [
"background.js","runtime.js"
]
},"browser_action": {
"default_popup": "index.html#/home","default_icon": "assets/icons/favicon-32x32.png","default_title": "title"
},"content_scripts": [
{
"matches": [ "<all_urls>" ],"js": [ "content_script.js" ]
}
],"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"
}
app-routing.module.ts:
const routes: Routes = [
{path: 'home',component: HomeComponent}
];
@NgModule({
imports: [RouterModule.forRoot(routes,{useHash: true})],exports: [RouterModule]
})
已编辑:
按照 wOxxOm 对评论的建议,我尝试向 popup.ts 添加编程注入,但它从内容脚本中给了我“1”的响应,它没有按应有的方式记录对象.
我试过这样:
Popup.ts(使用程序化注入):
sendMessagetoContentScript() {
chrome.tabs.query({currentwindow: true,function (tabs){
var activeTab = tabs[0];
chrome.tabs.executeScript(activeTab.id,{file: "content_script.js" },function (response) {
if (!chrome.runtime.lastError) {
var parsed_res = JSON.parse(response[0]);
console.log("content-script: " + parsed_res);
}
});
});
}
此程序化注入部分的内容脚本与我未编辑的问题部分的内容脚本文件相同。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。