Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject button into site (Chrome Extension content script)

I'm trying to inject a button onto a page using Chrome's content scripts, but the button never appears, and I get no error in the console.

My manifest.json file:

{
  "name": "Test",
  "version": "0.0.1",
  "manifest_version": 2,
  "description": "Test",
  "default_locale": "en",
  "permissions": [
    "<all_urls>"
  ],
  "content_scripts": [
    {
      "matches": [
        "<all_urls>"
      ],
      "js": [
        "src/inject/inject.js"
      ]
    }
  ]
}

and my inject.js file:

document.addEventListener('DOMContentLoaded', function () {
    var buttonOnSite = document.getElementById("buttonOnSite");
    var button = document.createElement("button");
    var text = document.createTextNode("test");
    button.appendChild(text);
    buttonOnSite.appendChild(button);
});

What I expect from the above code, is when I go to the site where a button with the id buttonOnSite exists, a new button, with the text test is created after it.

But nothing happens when I go to this site with the button! There is definitely a button with the id buttonOnSite (I've changed the ID for here, because it's a long ID).

I get no error message in the console, so what's wrong? It's probably something obvious, but I just can't see it. Any help is appreciated!

like image 553
downloader Avatar asked Jul 29 '14 21:07

downloader


2 Answers

By default, content scripts run after the DOM has loaded. This means that you’re adding your event listener after the event has fired, so your listener never hears it. Remove the first and last lines of your javascript.

like image 39
Teepeemm Avatar answered Oct 20 '22 01:10

Teepeemm


This is the code you need:

var buttonOnSite = document.getElementById("buttonOnSite"),
    parent = buttonOnSite.parentElement,
    next = buttonOnSite.nextSibling,
    button = document.createElement("button"),
    text = document.createTextNode("test");

button.appendChild(text);
if (next) parent.insertBefore(button, next);
else parent.appendChild(button);
like image 86
Marco Bonelli Avatar answered Oct 20 '22 01:10

Marco Bonelli