gpt4 book ai didi

javascript - chrome 扩展后台、js 到 content.js 之间的消息传递

转载 作者:行者123 更新时间:2023-12-03 01:30:27 25 4
gpt4 key购买 nike

我想在 Chrome 扩展程序 background.jscontent.js 之间发送消息。

背景看起来像这样:

setInterval(function(){
chrome.tabs.query({active: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id, {"message": "sample_msg"});
});
},
1000);

content.js 看起来像这样:

chrome.runtime.onMessage.addListener(function(message, sender) {
console.log('blablabla');
});

manifest.json 看起来像这样:

{
"manifest_version": 1,
"name": "Chrome Extension",
"description": "",
"version": "0.0.1",
"background": {
"scripts": [
"/src/background.js"
]
},
"content_scripts": [
{
"matches": [
"*://google.com/*"
],
"js": [
"/src/content.js"
],
"all_frames": true
}
],
"browser_action": {
"default_popup": "/src/popup.html"
},
"permissions": [
"<all_urls>",
"activeTab",
"tabs",
"cookies",
"background",
"contextMenus",
"unlimitedStorage",
"storage",
"notifications",
"identity",
"identity.email",
"webRequest",
"webRequestBlocking"
]
}

我读了很多,但我不明白为什么它不起作用?我可以帮忙吗?方向?评论?

最佳答案

sendMessage API 看起来正确,但 URL 匹配似乎有问题。

您的内容脚本将仅注入(inject) google.com 域,正如您在 list 文件中的 matches 键中提到的。

Open google.com and check the address bar you can see URL
https://www.google.com/, so to make your content script inject to google domain you need to change your matches

"matches": [
"https://*.google.com/*"
]

此外,更改您的 onMessage 监听器如下

chrome.runtime.onMessage.addListener( 
function(request, sender, sendResponse) {
console.log("Received message", request.message);
}
);

现在转到 google.com 并刷新页面。

关于javascript - chrome 扩展后台、js 到 content.js 之间的消息传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51334305/

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