Javascript 如何将数据从web应用程序(React)传递到chrome扩展(开发面板)

Javascript 如何将数据从web应用程序(React)传递到chrome扩展(开发面板),javascript,reactjs,google-chrome,google-chrome-extension,redux-devtools-extension,Javascript,Reactjs,Google Chrome,Google Chrome Extension,Redux Devtools Extension,我正在尝试制作一些类似Redux开发工具的东西。我想将数据从React应用程序传递到chrome扩展。数据应该通过扩展中的React render从React render函数传递。我试图在应用程序的窗口中设置变量(函数),以便在应用程序内部将其用作回调并将消息发送给扩展。现在我有以下架构: 内容脚本连接到扩展chrome.runtime.connect(runtimeId) 内容脚本注入web可访问的脚本: web可访问脚本设置窗口变量并将消息发送到后台脚本: 后台脚本侦听外部消息:

我正在尝试制作一些类似Redux开发工具的东西。我想将数据从React应用程序传递到chrome扩展。数据应该通过扩展中的React render从React render函数传递。我试图在应用程序的窗口中设置变量(函数),以便在应用程序内部将其用作回调并将消息发送给扩展。现在我有以下架构:

  • 内容脚本连接到扩展
    chrome.runtime.connect(runtimeId)
  • 内容脚本注入web可访问的脚本:
  • web可访问脚本设置窗口变量并将消息发送到后台脚本:
  • 后台脚本侦听外部消息:
    chrome.runtime.onMessageExternal.addListener
    并将数据发送到扩展应用程序(面板devtools)
一切正常,但此解决方案需要设置第二个域级别的外部可连接URL, (现在它只适用于localhost
“外部可连接”:{“匹配项”:[“*://127.0.0.1/*”]}

但我想在任何地方使用扩展。因此,我确信有另一个正确的解决方案可以做到这一点,但我仍然没有找到它。

您已经知道,外部可连接不允许这样做。因此,唯一的解决方案是使用内容脚本,然后内容脚本将消息中继到后台脚本。反之亦然。与注入的脚本通信
  var s = document.createElement("script");
  s.setAttribute("type", "text/javascript");
  s.setAttribute("src", file);
  document.documentElement.appendChild(s);
}
injectScript(chrome.extension.getURL("/scripts/war.js"), "body");
  const runtimeId = "";
    if (props) {
      chrome.runtime.sendMessage(runtimeId, JSON.stringify(props));
    }

};
window.testFunction = testFunction;
const port = chrome.runtime.connect(runtimeId);
port.postMessage({ props: JSON.stringify(data) });