Search code examples
javascriptgoogle-chrome-extension

How to make a chrome extension work immediately on a new page


I am trying to get my extension to act immediately upon a new page instead of when I click a button. For example, this code works in terms of changing the words on the page, but only once I click a button from my default popup. How can I make it to where it acts immediately once a user changes pages. I tried making a new .js file but it won't do anything.

function change(){
  const text = document.querySelectorAll("h1, h2, h3, h4, h5, p, li, td, caption, span, a")
for(let i=0;i<text.length;i++){
  if(text[i].innerHTML.includes("The")){
    text[i].innerHTML = text[i].innerHTML.replace("The","A")
  }
  
}
}
change();

Solution

  • Use content_scripts.

    manifest.json

    {
      "name": "hoge",
      "version": "1.0",
      "manifest_version": 3,
      "content_scripts": [
        {
          "matches": [
            "<all_urls>"
          ],
          "js": [
            "matches.js"
          ]
        }
      ]
    }
    

    matches.js

    function change(){
      const text = document.querySelectorAll("h1, h2, h3, h4, h5, p, li, td, caption, span, a")
    for(let i=0;i<text.length;i++){
      if(text[i].innerHTML.includes("The")){
        text[i].innerHTML = text[i].innerHTML.replace("The","A")
      }
      
    }
    }
    change();