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!
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With