如何在background.js 和popup.js 之间进行通信?

2024-01-11

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

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

和内容脚本:

"content_scripts": [
    {
      "matches": ["*://*/*"],
      "js": ["scripts/content_script.js"]
    }
  ],

弹出窗口(popup.html)和一个弹出脚本(popup.js)。 popup.js 未注册到清单中,它处理 popup.html 外观,并监听 popup.html 中的用户操作,例如单击按钮。

我想延期,什么通过电子邮件发送当前选项卡的页面,为此,我需要使用以下命令获取页面 DOMcontent_script,将数据(DOM)传递给background script。之后,当用户触发popup.html中的事件时,popup.js会捕获该事件,并且我希望popup.js能够从background.js获取传递的数据(DOM)。我怎样才能做到这一点?所以,我的问题是,如何在 background.js 和 popup.js 之间进行通信?


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

谢谢埃尔维斯,我想我解决了这个问题;我只需要在内容脚本中获取网站的 DOM,但我的问题的解决方案是这样的:

内容脚本.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>

popup.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
}

谢谢您的帮助 ;)


您可以进行消息传递。来自文档 https://code.google.com/chrome/extensions/messaging.html:

在您的内容脚本中使用它:

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函数将被传递给回调

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在background.js 和popup.js 之间进行通信? 的相关文章