如何在Active Tab的Chrome扩展程序中将消息从Popup.js发送到内容脚本?

时间:2019-06-21 04:34:13

标签: google-chrome-extension

当我从chrome扩展程序中单击工具栏图标时,它将弹出默认的popup.html和popup.js。我想从该popup.js发送一条消息到当前的活动选项卡。我不知道如何获得活动标签。

我在popup.js中的代码如下:

window.onload = function() {
  console.log(`popup.js:window.onload`);
  const timeNow = document.getElementById("timeNowId");
  timeNow.innerText = new Date().toLocaleTimeString();
  var resultsButton = document.getElementById("buttonId");
  resultsButton.onclick = () => {
    chrome.runtime.sendMessage(
      "FromPopupToBackgroundToContent:" + timeNow.innerText,
      function(response) {
        response === undefined
          ? alert("popup.js:return from sendMessage:undefined")
          : alert("popup.js:return from sendMessage:", response);
      }
    );
  };
};

完整的,无法正常工作的示例位于该分支链接的github存储库中。

https://github.com/pkellner/chrome-extension-message-popup-to-content/tree/feature-popup-to-content-directly-getcurrent

1 个答案:

答案 0 :(得分:0)

示例:

popup.js

 function popup() {
    chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
    var activeTab = tabs[0];
    chrome.tabs.sendMessage(activeTab.id, {"message": "start"});
   });
}

document.addEventListener("DOMContentLoaded", function() {
  document.getElementById("button1").addEventListener("click", popup);
});

content.js

chrome.runtime.onMessage.addListener(
      function(request, sender, sendResponse) {
        if( request.message === "start" ) {
         start();
             }
      }
    );

    function start(){
        alert("started");
    }

popup.html

<!DOCTYPE html>
<html>
    <head></head>
    <script src="popup.js"></script>
    <body>
        <input id="button1" type=button value=clickme>
    </body>
</html>