Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js Chrome Extension - How to store data from Background.js in a variable inside React?

Hello what I am trying to do is send a string that I derived from my background.js file and send it to my react app (specifically a component used by App.js). I have /* global chrome */ at the top of the component.js file and am able to store data on the chrome local storage however my question is how do I make sure that I can store this data in a variable before the React app is processed? For example, even though I am able to assign a variable inside the component the data from chrome storage, it is only stored after my React app is created. What I'm trying now is to send a chrome message in background.js and try to listen for this message in the component to store the variable however the listener does not seem to be working. Any help would be appreciated! (p.s. this is using functional components but help in class components would also be appreciated)

component.js:

chrome.runtime.onMessage.addListener(function(msg) { 
   if(msg.type == "USER_STORED") {
      chrome.storage.local.get(['name'], function(result) { 
         console.log("User is " + result.name); 
         username = result.name; 
      }); 
   }
});

background.js:

chrome.storage.local.set({name: username}, function() { 
      console.log("User is set to " + username);
      chrome.runtime.sendMessage({type: "USER_STORED" });
      console.log("message sent"); 
    }); 

    // Open extension window
    console.log("WINDOW_OPENED"); 
    var win = window.open("index.html", "extension_popup"); 

Console: Extension console image

like image 774
struggleatreact Avatar asked Jun 29 '26 22:06

struggleatreact


1 Answers

You use wrong approach. You don't need to send such messages from background at all, nor need to listen for them in your popup window. Just add chrome.storage.local.get call into your popup entry point (likely index.js) and wrap ReactDOM.render with its callback. Something like this:

chrome.storage.local.get(null, function (data) {
  ReactDOM.render(
    <App {...data} />,
    document.getElementById('root')
  )
});

Then, the data from chrome.storage will be available in all sub-components of the root <App> via props. Something like this:

function YourComponent(props) {
  console.log("User is " + props.name);
  return <h1>Hello, {props.name}</h1>;
}
like image 166
hindmost Avatar answered Jul 02 '26 12:07

hindmost



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!