Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)?

like image 396
Forge Avatar asked Mar 21 '16 16:03

Forge


People also ask

How do I add buttons to Chrome?

Click the Google Chrome menu, which looks like three horizontal lines at the upper right of the browser, and then select "Settings" to configure Chrome. Check "Show Home Button" from the Appearance section to add the Home button to the toolbar.

How do I inject a JavaScript extension in Chrome?

To run a script: - Open the extension and click the play button. Or - Run a script from the context menu. Right Click > Select Scripty > Select your script.


1 Answers

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);
like image 162
Haibara Ai Avatar answered Sep 18 '22 04:09

Haibara Ai