首页 > 解决方案 > 每次加载页面时,如何从后台向 Chrome 扩展程序中的弹出窗口发送消息?

问题描述

我可以通过以下方式从弹出窗口向后台发送消息:

背景.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!"
  }
});

警报加载正常但我需要做相反的事情。我希望后台在加载页面时发送一个 api 调用,并将该 api 调用的结果发送到 popup.js,以便它可以对 DOM 进行更改。当我切换上面的代码时,没有显示警报。我的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
}

标签: javascriptgoogle-chromegoogle-chrome-extension

解决方案


从技术上讲,chrome.runtime.sendMessage将向包括弹出窗口在内的所有扩展页面发送消息,但这不是应该组织通信的方式。

请注意,弹出窗口仅在显示时才会运行,因此如果隐藏它就无法接收消息。

假设弹出窗口已经可见,解决方案通常是简单地等待后台脚本的响应,使用return true.

popup.js 发送一条消息:

chrome.runtime.sendMessage({foo: 'bar'}, response => {
  // use the response here
});

背景脚本:

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});
  });
}

推荐阅读