0

I'm building a Google Chrome Extension with Reactjs. I want to get a text from the DOM Element with a selector #firstHeading and show the text inside my chrome extension.

This is the URL I'm using https://en.wikipedia.org/wiki/Erasmus_Sch%C3%B6fer

I'm using Manifest version 3

Here is what I have done so far.

manifest.json

{
    "name": "Wiki Title",
    "version": "0.01",
    "description": "grab page content",
    "action": {
        "default_popup": "popup.html"
    },
    "content_scripts": [
        {
            "matches": [
                "<all_urls>"
            ],
            "js": [
                "./scripts/contentScript.js"
            ],
            "run_at": "document_end"
        }
    ],
    "manifest_version": 3,
    "permissions": [
        "tabs",
        "activeTab"    ]
}

contentScript.js

if (window.location.href.includes("wikipedia.com")) {
  let articleTitle = document.querySelector("#firstHeading");
  if (typeof articleTitle != "undefined" && articleTitle != null) {
    const articleTitle = document.querySelector(
      "#firstHeading"
    ).innerText;
    console.log(articleTitle);
  }
}

With the above code, I can see the Article Title inside the console log.

Since I'm using React js for my chrome extension. I'm not sure how to pass this text inside the App.js file.

Right now my folder structure looks like this.

enter image description here

Ava Juan
  • 113
  • 1
  • 9
  • Either include the data as props passed to your app in the initial render in `index.js` or use the [effect hook](https://reactjs.org/docs/hooks-reference.html#useeffect) to get the data on first render of your app inside the component where you use it. Can you link us to your full code repo in GitHub? What you've shown is not enough information for a good answer. See [How to create a Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example) – jsejcksn Jul 24 '22 at 05:12
  • The part of the problem that relates to extensions is quite clear: 1) remove `content_scripts` from manifest.json and contentScript.js, 2) use executeScript to extract the data right in your popup script (popup.js), [examples](https://stackoverflow.com/a/67227376/). – wOxxOm Jul 24 '22 at 06:29

0 Answers0