0

I'm trying to learn how to make chrome extensions and have been trying to learn with the new manifest v3 as my understanding is it'll be the norm in the future. A lot of the documentation has been pretty brutal though and seems to be behind.

I am looking to make a simple extension that finds specific keywords on a website. I want to find the text which matches a specific html id whenever a user visits a website.

Currently, my background script calls on a separate content script to discover when the website the user has navigated to matches the website I want to search on. If I arrive at the appropriate website then another content script is called which searches the website.

Here is the relevant code from my background script:

if (onSite){
  scrapeSite(onSite);
}

onSite is only ever true/active when it is populated with the url of the site I want to visit.

The relevant code for scrapeSite is

function scrapeSite{
   try {
    book = document.getElementById("bookTitle");
    if (book){
     console.log(`${book}`);
     }
    }
    catch(err) {
      console.log(`No Book Title Found`);
      console.log(`${book}`);
     }
    }
}

If I remove the catch(err) then the console log outputs the following Error handling response: ReferenceError: document is not defined at scrapeSite

I'm really just trying to learn here so would appreciate any suggestions regarding better documentation, recommended stackoverflow questions etc. Also if you've been learning manifest v3 and have suggestions for good documentation/tutorials in general that would be great.

  • Remove the background script and use a [content script](https://developer.chrome.com/extensions/content_scripts). – wOxxOm May 24 '21 at 14:50
  • @wOxxOm my understanding was that this method of doing it was implementing a content script but as a function in the background script. Is there a different way I should be calling the content script? As it stands I currently have scrapeSite in a different js file then the background.js but I use importScripts at the top of my background.js to allow me to call on it. – Warwick Logan May 24 '21 at 15:11
  • There's no need for the background script here. Use a content script declared in manifest.json. See also [How to access the webpage DOM rather than the extension page DOM?](https://stackoverflow.com/a/4532567) – wOxxOm May 24 '21 at 15:13
  • I supposed this highlights a greater misunderstanding on my part regarding content scrips and background scripts. I would still need to call the content script from the background script correct? Or is there some other method? What method would you recommend? I appreciate the help! – Warwick Logan May 24 '21 at 15:34
  • As the documentation and the answer I've linked show, you can simply declare the content script and it runs in the matching web page automatically. – wOxxOm May 24 '21 at 15:47

0 Answers0