How to manipulate the DOM through an extension?

Asked

Viewed 444 times

1

I’m starting to work with extensions in Google Chrome and after some time reading tutorials I so far could not access anything in the DOM of the page. I need to modify the CSS of the page or run some script within it. Could someone pass me some example?

I’m looking for something like that:

index.html

<html>
   <head>
       <title>teste de extensão</title>
   </head>
   <body>
      <button id="btn1" onclick="fundoAzul()">fundo azul</button>
      <br>
      <button id="btn1" onclick="fundoVermelho()">fundo vermelho</button>
      <script>
          function fundoAzul(){
            document.querySelector('body').style.background = 'blue';
          };
          function fundoVermelho(){
            document.querySelector('body').style.background = 'red';
          };
      </script>
   </body>
</html>

In the tutorials I saw, one of them showed me how to make a alert (I can’t remember which one now) but mine alert was executed within the extension and not on the current page.

1 answer

2


You need to use Content Scripts. See a basic example:

manifest.json:

{
    "name": "Exemplo StackOverflow",
    "description": "Demonstração de como utilizar content_script",
    "version": "0.1",
    "content_scripts": [{
        "matches": ["http://answall.com"],
        "js": ["script.js"],
        "run_at": "document_end"
    }],
    "manifest_version": 2
}

script.js:

document.body.style.background = 'red';
  • dude, fantastic this really now worked! now I can create my extension without fear of being happy rsrs, thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.