chrome-extension-boilerplate-react icon indicating copy to clipboard operation
chrome-extension-boilerplate-react copied to clipboard

How to inject custom components to content scripts?

Open edmund-io opened this issue 1 year ago • 1 comments

Hi there, I am currently trying to do some DOM manipulation / display custom components within www.example.com.

I know that in order to modify the DOM elements within a certain domain the work would need to be done within the src/pages/Content directory, but I'm struggling to figure out how would I go about injecting custom React components into there. Is this even a possible thing to do or do I have the wrong idea about Chrome's content scripts?

Thank you!

edmund-io avatar Apr 22 '23 14:04 edmund-io

To inject React components into a site using a content script, you will need to call React's createRoot on a particular DOM node, which gives React the ability to manipulate the contents of the DOM node.

Let's say we have a document which looks like the following:

<html>
  <body>
     <div id="container">
       <div id="content">Some content</div> 
    </div>
  </body>
</html>

And you want to inject your React component App into the div with id container

Your content script could look something like this:

import React from 'react';
import { createRoot } from 'react-dom/client';

import App from './App.jsx';

const containerEl = document.getElementById("container");
const reactRootEl = document.createElement("div");
reactRootEl.setAttribute("id", "reactRoot");
containerEl.appendChild(reactRootEl);

const reactRoot = createRoot(reactRootEl);
reactRoot.render(<App/>);

Hope this helps!

lowenhere avatar Jun 10 '23 06:06 lowenhere