更新时间:2023-12-05 20:08:46
我认为我的问题已被修正
chrome.tabs.sendMessage(tabId, {action:'test'},
注意,我错误地使用 msg
,而不是 action
在上述问题中。 另外,我不使用第三个参数sendResponse以避免全双工通信
我只需将内容脚本中的另一条消息发送回后台页面。
从内容脚本中,使用以下命令将消息发送到后台页面:
函数SendMessageToBackgroundPage(data)
{
chrome.runtime.sendMessage({
action:'功夫',
来源:'熊猫'
});
使用以下代码在背景页面中抓取它:
chrome.runtime.onMessage.addListener(
函数(request,sender,sendResponse){
switch(request.action){
'kungfu':alert(request.source);
}
});
I was experimenting with chrome extension. My goal is to send a message from background script to injected script and let the injected script return back the result.
Code is as below:
background.js
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab){
chrome.tabs.executeScript(tabId, {'file': "content.js"},
function(){
chrome.tabs.sendMessage(tabId, {msg: 'test'},
function(response){
console.log(response);
}
);
return true;
}
);
});
content.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
sendResponse('test message');
return true;
}
);
I get the error message
Could not send response: The chrome.runtime.onMessage listener must return true if you want to send a response after the listener returns
when calling sendResponse
inside content.js
I am already returning true from the listener.. confused?
Am I missing something obvious?
I think my issue was fixed by
chrome.tabs.sendMessage(tabId, {action: 'test'},
Note, I incorrectly use msg
instead of action
in above question.
Also, I do not use the third parameter sendResponse to avoid full-duplex communication I simply post another message from content script back to background page.
From content script, send message to background page using:
function SendMessageToBackgroundPage(data)
{
chrome.runtime.sendMessage({
action: 'kungfu',
source: 'panda'
});
}
Catch it inside background page using:
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
switch (request.action) {
case 'kungfu': alert(request.source);
}
});