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? #123

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

How to inject custom components to content scripts? #123

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!

@DavidNaak
Copy link

I wasn't able to figure out how to do it with this repo, but you can do it like this:

You put this in your content script (example for youtube)

async function injectReactApp() {
  try {
    const youtubeElement = await waitForElm(
      "#secondary.style-scope.ytd-watch-flexy"
    );

    let app = document.getElementById("myReactApp");

    if (app) {
      app.remove();
    }

    app = document.createElement("div");
    app.id = "myReactApp";

    // Append the new div to the YouTube page.
    youtubeElement.insertAdjacentElement("afterbegin", app);

    // Use ReactDOM.render to render your React application into the new div.
    ReactDOM.render(<App fetchData={fetchData} />, app);
  } catch (error) {
    console.log("Error:", error);
  }
}

window.onload = () => {
  if (window.location.hostname === "www.youtube.com") {
    if (
      window.location.search !== "" &&
      window.location.search.includes("v=")
    ) {
      injectReactApp();
    }
    
}

But you will have to figure out how to put the contentScript in your webpack config

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