lxieyang / chrome-extension-boilerplate-react

A Chrome Extensions boilerplate using React 18 and Webpack 5.
MIT License
3.42k stars 1.07k forks source link

How to inject custom components to content scripts? #166

Open edmund-io opened 1 year ago

edmund-io commented 1 year ago

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!

lowenhere commented 1 year ago

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!