[英]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. 我正在使用
content scripts
,我想向网页注入一个按钮。
This is my manifest.json
: 这是我的
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
: 这是
popup.html
:
<html>
<body>
<input type="button" id="button" style="display:none;">
</body>
</html>
And script.js
: 和
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. 当转到
http://127.0.0.1:8000
我看到背景更改为黄色,但它找不到按钮,因为它不是我本地服务器所服务的网页的一部分。 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)? 我应该怎么做才能在
http://127.0.0.1:8000
内容的顶部注入一个按钮(假设我不知道它的内容)?
To insert a button, just create it in you content scripts and insert it, you needn't(shouldn't) declare it in popup.html
要插入按钮,只需在内容脚本中创建并插入它,您就不需要(不应该)在
popup.html
声明它
manifest.json 的manifest.json
{
"manifest_version": 2,
"name": "my extension",
"content_scripts": [
{
"matches": ["http://127.0.0.1:5000/*"],
"js": ["script.js"]
}
]
}
script.js 的script.js
document.body.style.backgroundColor = "yellow";
var button = document.createElement("button");
document.body.appendChild(button);
You should add a "run_at": "document_end"
in your content_scripts
property 您应该在
content_scripts
属性中添加"run_at": "document_end"
In document_end
, the script files will then be injected after the DOM is complete. 在
document_end
,然后在DOM完成后注入脚本文件。 This way the document
will be able to find your lost button :) 这样
document
就能找到丢失的按钮:)
"content_scripts": [
{
"matches": ["http://127.0.0.1:5000/*"],
"js": ["script.js"],
"run_at": "document_end"
}
]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.