Peter Kellner
Peter Kellner

Reputation: 15478

How To Send a Message From Popup.js to Content Script in Chrome Extension on Active Tab?

When I click on the toolbar icon from my chrome extension, it brings up the default popup.html along with popup.js. From that popup.js, I want to send a message to the current active tab. I can't figure out how to get the active tab.

My code in the popup.js looks like this:

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);
      }
    );
  };
};

The full, non-working example is in this github repo at this branch linked to.

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

Upvotes: 0

Views: 1225

Answers (1)

Umbro
Umbro

Reputation: 2204

Example:

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>

Upvotes: 3

Related Questions