Javascript 无法在另一个消息扩展插件中发送消息
我在chrome扩展的背景页面中传递消息时遇到了麻烦 在内容页中 我发送消息并等待后台页面的响应:Javascript 无法在另一个消息扩展插件中发送消息,javascript,google-chrome,asynchronous,google-chrome-extension,Javascript,Google Chrome,Asynchronous,Google Chrome Extension,我在chrome扩展的背景页面中传递消息时遇到了麻烦 在内容页中 我发送消息并等待后台页面的响应: chrome.runtime.sendMessage({"name": "Calling"}, function (response) { console.log(response); }); 在背景页面中 我有一个事件侦听器来侦听内容页中的消息: chrome.runtime.onMessage.addListener( function (request, sender, s
chrome.runtime.sendMessage({"name": "Calling"}, function (response) {
console.log(response);
});
在背景页面中
我有一个事件侦听器来侦听内容页中的消息:
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if (request.name == "Calling") {
doTask().then(function (message) {
sendResponse(message);
});
return true; // Make respond asynchronously
}
}
);
在“调用”事件侦听器中,我调用函数doTask()
,该函数返回一个承诺:
var doTask = function(){
return new Promise(function (resolve) {
chrome.runtime.sendMessage({"name": "DoTask"}, function (response) {
resolve(response);
});
});
};
在doTask()
内部,我发送另一条消息“doTask”,并等待响应
chrome.runtime.onMessage.addListener(
function (request, sender, sendResponse) {
if (request.name == "DoTask") {
var message = "Task has done!";
sendResponse(message);
return true; // Make respond asynchronously
}
}
);
我希望“任务已完成!”将打印在内容页中,但不会显示任何内容!调试时,我意识到“DoTask”事件侦听器无法接收任何消息
这里怎么了?多谢各位
p/S:我确保所有脚本都被注入
manifest.json
代码是正确的。确保内容脚本已实际插入:重新加载扩展后,您需要重新加载选项卡或通过chrome.tabs.executeScript重新插入。不过需要注意的是,doTask
使用chrome.runtime.sendMessage将消息发送到另一个扩展页面,该页面必须与发送消息的页面不同(要发送到同一页面,只需将onMessage回调提取为单独的函数并直接调用即可)。如果要将其发送到内容脚本,请使用chrome.tabs.sendMessage和tabId作为第一个参数。因此,无法在同一扩展页面中发送消息?我必须移动“DoTask”事件侦听器到另一个扩展页?只需直接调用该函数,请另找时间,请为每个文件使用一个代码块。不要为每个函数将文件拆分为单独的代码块。当我们可以确定哪些内容与哪些内容组合在一起时,更容易理解代码。我们都非常熟悉阅读代码。我们通常不需要这样做在代码中穿插不同的功能和解释性文本。如果有人需要这些文本来理解您的代码,那么它应该作为注释包含在代码中,以便任何阅读实际代码的人都能够理解它。