问题
I can send a message from a popup to a background via:
background.js
chrome.runtime.onMessage.addListener(
function(request) {
alert(request.data.subject);
}
);
popup.js
chrome.runtime.sendMessage({
msg: "something_completed",
data: {
subject: "Loading...",
content: "Just completed!"
}
});
The alert loads fine BUT I need to do the opposite. I would like the background to send an api call when a page is loaded and send the results of that api call to the popup.js so that it can make changes to the DOM. When I switch the above code, no alert is shown. My manifest.json
:
{
"name": "example",
"version": "0.0.1",
"description": "Chrome Extension's message passing example",
"browser_action": {
"default_icon": "images/get_started32.png",
"default_popup": "popup.html"
},
"background": {
"scripts": ["background.js"]
},
"content_scripts":[{
"matches":["http://*/*", "https://*/*"],
"js":["popup.js"]
}],
"permissions": [
"background","webRequest","webRequestBlocking","webNavigation","tabs","notifications"
],
"manifest_version": 2
}
回答1:
Technically, chrome.runtime.sendMessage will send a message to all extension pages including the popup, however this is not how the communication should be organized.
Note, the popup is running only when shown so if it's hidden it can't receive messages.
Assuming the popup is already visible, the solution is usually to simply wait for the background script's response using return true
.
popup.js sends a message:
chrome.runtime.sendMessage({foo: 'bar'}, response => {
// use the response here
});
background script:
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg.foo === 'bar') {
doSomeProcessing(msg).then(sendResponse);
return true;
}
});
function doSomeProcessing(msg) {
return new Promise(resolve => {
// do something async
resolve({data: 123});
});
}
来源:https://stackoverflow.com/questions/59385472/how-do-i-send-a-message-from-the-background-to-a-popup-in-a-chrome-extension-eve