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

时间:2012-05-01 09:47:43

标签: javascript google-chrome-extension

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

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

和内容脚本:

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

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

我想做一个扩展,通过电子邮件发送当前标签的页面,为此,我需要使用content_script获取页面DOM,将数据(DOM)传递给background script。在此之后,当用户在popup.html中触发事件时,popup.js会捕获此事件,并且我希望popup.js能够从background.js获取传递的数据(DOM)。我怎么能这样做?所以,我的问题是,我如何在background.js和popup.js之间进行通信?


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

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

content_script.js

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

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

感谢您的帮助;)

1 个答案:

答案 0 :(得分:4)

您可以进行消息传递。来自documentation

在内容脚本中使用此功能:

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

相关问题