如何在后台.js和弹出窗口.js之间进行通信

How can I communicate between background.js and popup.js?

本文关键字:js 之间 窗口 通信 后台      更新时间:2023-09-26

我有一个扩展,带有后台脚本:

"background": {
    "scripts": ["scripts/background.js"]
  },

和内容脚本:

"content_scripts": [
    {
      "matches": ["*://*/*"],
      "js": ["scripts/content_script.js"]
    }
  ],
弹出窗口

(popup.html),弹出窗口脚本(popup.js) . popup.js 未注册到清单中,它处理弹出窗口.html查看和侦听在弹出窗口中执行的用户操作.html例如单击按钮。

我想制作一个扩展名,向当前选项卡的页面发送电子邮件,为此,我需要获取带有content_script的页面 DOM,将数据 (DOM( 传递给background script。在此之后,当用户在 popup.html 中触发事件时,popup.js 会捕获此事件,我希望 popup.js 能够从后台获取传递的数据 (DOM.js。我怎么能做到这一点?所以,我的问题是,我如何在背景.js和弹出窗口.js之间进行通信?


我找到了自己问题的答案:

谢谢猫王,我想我解决了问题;我只需要在内容脚本中获取站点的 DOM,但我的问题的解决方案是这样的:

content_script.js

 // SEND DOM structure to the background page
    chrome.extension.sendRequest({dom: "page DOM here"});

背景.html

<html>
<head>
<script>
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    if(request.dom != "")
        var theDOM = request.dom;
        console.log(request.dom); // page DOM here -> works
        chrome.extension.sendRequest({theDOM: theDOM}); // theDOM : "page DOM here"
});
</script>
</head>
<body>
</body>
</html>

弹出窗口.js

var dom;
chrome.extension.onRequest.addListener(function(request, sender, sendResponse) {
    if(request.theDOM != ""){
        console.log("popup request: "+request.theDOM);
        dom = request.theDOM;
    }
});
// HANDLE TAB_1 REQUESTS (EMAIL PAGE)
// ---------------------------------
$("#send").click(function(){
    console.log(dom); // page DOM here
}

感谢您的帮助;)

您可以执行消息传递。从文档中:

在内容脚本中使用它:

chrome.extension.sendRequest({greeting: "hello"}, function(response) {
  console.log(response.farewell);
});

它将{greeting: "hello"}发送到后台。注意指定的回调

后台页面可以使用以下命令侦听这些请求:

chrome.extension.onRequest.addListener(
  function(request, sender, sendResponse) {
    if (request.greeting == "hello")
      sendResponse({farewell: "goodbye"});
  });

sendResponse函数的参数将传递给回调