How do I send a message from the background to a popup in a Chrome extension everytime a page gets loaded?

南笙酒味 提交于 2021-02-08 11:29:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!