Forge
Forge

Reputation: 6834

How to inject a button to a webpage with Chrome Extension

I'm using content scripts and I would like to inject a button to a webpage.

This is my manifest.json:

{
  "manifest_version": 2,
  "name": "my extension",
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": [
    "activeTab"
  ],
  "content_scripts": [
      {
        "matches": ["http://127.0.0.1:8000/*"],
        "js": ["script.js"],
        "run_at": "document_end"
      }
  ]
}

This is popup.html:

<html>
  <body>
    <input type="button" id="button" style="display:none;">
  </body>
</html>

And script.js:

document.body.style.backgroundColor = "yellow";
var button = document.getElementById("button");
button.style.visibility = "visible";

When going to http://127.0.0.1:8000 I see the background changes to yellow, however it doesn't find button because it's not part of the webpage served by my local server. It shows this error:

Uncaught TypeError: Cannot read property 'style' of null

What should I do to inject a button on top of the content in http://127.0.0.1:8000 (assuming I don't know its content)?

Upvotes: 5

Views: 10327

Answers (2)

Haibara Ai
Haibara Ai

Reputation: 10897

To insert a button, just create it in you content scripts and insert it, you needn't(shouldn't) declare it in popup.html

manifest.json

{
  "manifest_version": 2,
  "name": "my extension",
  "content_scripts": [
      {
        "matches": ["http://127.0.0.1:5000/*"],
        "js": ["script.js"]          
      }
  ]
}

script.js

document.body.style.backgroundColor = "yellow";
var button = document.createElement("button");
document.body.appendChild(button);

Upvotes: 9

Poul Kruijt
Poul Kruijt

Reputation: 71911

You should add a "run_at": "document_end" in your content_scripts property

In document_end, the script files will then be injected after the DOM is complete. This way the document will be able to find your lost button :)

"content_scripts": [
      {
        "matches": ["http://127.0.0.1:5000/*"],
        "js": ["script.js"],
        "run_at": "document_end"
      }
  ]

Upvotes: 2

Related Questions