S
S
Sergey Levchenko2021-05-26 20:44:44
Google Chrome
Sergey Levchenko, 2021-05-26 20:44:44

How to pass messages from popup.js to content.js?

Good afternoon! I've been struggling for more than a day just to learn how to pass messages in an extension, I just can't catch up with how it works. How to send an event from popup js to content js? The essence is simple how to make it so that the image from the popup is placed on the active page of the browser in the first div element

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nadim Zakirov, 2021-05-26
@Levchenski

To send a message from the popup window to the content script, you need to execute in the popup window:

chrome.tabs.query({}, function(tabs) {
  for (i = 0; i < tabs.length; i++) {
    chrome.tabs.sendMessage(tabs[i].id, 'Сообщение, которое нужно передать');
  }
});

The code above loops through all tabs and sends the specified message to all existing tabs.
On the side of the content script to receive a message, there must be a handler:
chrome.extension.onMessage.addListener(function(msg) {
  console.log('Принято сообщение: ' + msg);
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question