gpt4 book ai didi

javascript - Chrome 扩展 : Unable to pass message to content. js

转载 作者:行者123 更新时间:2023-11-27 23:49:33 24 4
gpt4 key购买 nike

我正在尝试从background.js 向content.js 发送消息。content.js 中的 addListener 不起作用。

背景.js

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) 
{
console.log(tab.url);
if(changeInfo.status=="complete"){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
if(tabs.length!=0){
chrome.tabs.sendMessage(tabs[0].id, {message: "sendurl"}, function(response) {
console.log(response.url);
});
}
});
console.log("load complete");
}
});

content.js

chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
if( request.message === "sendurl" ) {
var firstHref = $("a[href^='http']").eq(0).attr("href");

console.log(firstHref);
sendResponse({url: firstHref});
}
}
);

ma​​nifest.json

   "background": {
"scripts": ["background.js"]
},
"content_scripts": [
{
"matches": ["https://*/","http://*/"],
"js": ["jquery-2.1.4.js","enc-base64-min.js","hmac-sha256.js","content.js"]

}
],

一段时间后,出现错误:TypeError: Cannot read property 'url' of undefined

最佳答案

您的 "matches": ["https://*/","http://*/"], 仅指定域通配符,这意味着内容脚本是为主注入(inject)的仅页面。您看到的错误消息是因为 sendMessage 一段时间后超时,因为没有内容脚本来接收消息。

the match pattern documentation说:

http://*/* Matches any URL that uses the http scheme

正确的代码是"matches": ["https://*/*","http://*/*"],

附注利用the debugger ,捕获此类错误非常有帮助。

关于javascript - Chrome 扩展 : Unable to pass message to content. js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32845306/

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