Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to inject custom components to content scripts? #166

Open
edmund-io opened this issue Apr 22, 2023 · 1 comment
Open

How to inject custom components to content scripts? #166

edmund-io opened this issue Apr 22, 2023 · 1 comment

Comments

@edmund-io
Copy link

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
Copy link

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants