[英]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. 我正在尝试使用Chrome的内容脚本在页面上注入一个按钮,但按钮从未出现,我在控制台中没有出现任何错误。
My manifest.json
file: 我的
manifest.json
文件:
{
"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: 和我的
inject.js
文件:
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. 我对上述代码的期望是,当我访问一个id为
buttonOnSite
的按钮存在的网站时,会出现一个新按钮,并在其后创建文本test
。
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). 肯定有一个带有id
buttonOnSite
的按钮(我在这里更改了ID,因为它是一个很长的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!
任何帮助表示赞赏!
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);
By default, content scripts run after the DOM has loaded. 默认情况下,内容脚本在加载DOM后运行。 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.
删除javascript的第一行和最后一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.