Skip to content Skip to sidebar Skip to footer

How To Pass Data From Content Script To Popup.html?

I'm learning how to make chrome extensions. I have a content script that will obtain some data and I want to pass them to the popup.html page to display them on the popup DOM. I've

Solution 1:

In general, it will not work to send a message from a content script to a popup unless you know the popup is open: the popup does not exist until you open it.

Given this, it will likely be most decoupled to have your content script send its message to a persistent background (which is the default btw) and serve as the repository for your messages until the popup requests them.

background.js

const messageQueue = [];
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  // Arbitrary string allowing the background to distinguish// message types. You might also be able to determine this// from the `sender`.if (message.type === 'from_content_script') {
    messageQueue.push(message);
  } elseif (message.type === 'from_popup') {
    sendResponse(messageQueue);
  }
});

Now from content script, send chrome.runtime.sendMessage({imageURIs: l, type: 'from_content_script'}... and from the popup send

chrome.runtime.sendMessage({type: 'from_popup'}, (response) => {
  // do stuff with response (which will be the value of messageQueue// sent from background.js).
});

Of course the strings 'from_popup' and 'from_content_script' mean nothing; they are just there for clarity.

If you need the popup to initiate the flow, you will need to:

  • send a message from the popup
  • to the background, to send a message to the content scripts
  • which should respond to the background
  • which should respond to the popup

Solution 2:

Chrome runtime have not onMessage method please see this link,hope this will hep you

Post a Comment for "How To Pass Data From Content Script To Popup.html?"