Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To send information to a React component from the background.js in a React Chrome Extension, you can use the messaging system provided by the Chrome API.

Here's an example of how to do it:

  1. In your background.js file, get the ID of the tab you want to send information to. You can use the chrome.tabs API for this:

    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
     var tabId = tabs[0].id;
     // send message to the content script in the tab
     chrome.tabs.sendMessage(tabId, {data: 'hello'});
    });
    
  2. In your content script (where your React component is rendered), listen for the message using the chrome.runtime.onMessage API:

    chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
     // check the message for the data you want
     if (request.data === 'hello') {
       // update the state of the React component
       this.setState({message: request.data});
     }
    });
    
  3. Make sure you have access to the state of your React component in your content script. You can do this by using the window.postMessage API to send data from your React component to your content script.

    // in your React component
    componentDidMount() {
     // send a message to the content script to register the listener
     window.postMessage({type: 'register'}, '*');
    }
    
    handleMessage(event) {
     if (event.source !== window) return;
     if (event.data.type === 'stateUpdate') {
       // update the state of the React component
       this.setState({message: event.data.state.message});
     }
    }
    window.addEventListener('message', this.handleMessage.bind(this));
    
  4. Finally, in your content script, listen for the state updates sent from your React component using the window.addEventListener API:

    window.addEventListener('message', function(event) {
     if (event.source !== window) return;
     if (event.data.type === 'register') {
       // send the current state to the React component
       chrome.runtime.sendMessage({type: 'stateUpdate', state: {message: 'hello'}});
     }
    });