javascript Chrome 扩展 - 用于在任何页面上运行 js 的简单内容脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19347499/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Chrome Extension - Simple Content Script for running js on any page
提问by user2876479
How can I write a simple Chrome Extension content script that will execute JavaScript (for example alert("hello");
) on every page load?
如何编写一个简单的 Chrome 扩展内容脚本,该脚本将alert("hello");
在每个页面加载时执行 JavaScript(例如)?
So when I navigate to a page or reload a page, the JavaScript should run.
所以当我导航到一个页面或重新加载一个页面时,JavaScript 应该运行。
This is my manifest.json
file so far:
manifest.json
到目前为止,这是我的文件:
{
"name": "Highlight some phrases",
"description": "Hightlight some pre defined text from websql database after page loads",
"version": "0.1",
"permissions": [
"tabs","<all_urls>"
],
"browser_action": {
"default_icon": "icon.png",
"default_popup": "popup.html"
},
"content_scripts": [
{
"matches": [
"http://*/*",
"https://*/*"
],
"js": ["content.js"]
}
],
"background": {
"page": "background.html"
},
"manifest_version": 2
}
回答by yakiang
If all you need is to alert hello
on every page load or reload, below is a simple demo:
Manifest.json
:
如果您只需要hello
在每个页面加载或重新加载时发出警报,下面是一个简单的演示
Manifest.json
:
{
"name": "Highlight some phrases",
"description": "Hightlight some pre defined text after page loads",
"version": "0.1",
"permissions": [
"tabs","<all_urls>"
],
"browser_action": {
"default_icon": "icon.png"
},
"content_scripts": [
{
"matches": [
"http://*/*",
"https://*/*"
],
"js": ["content.js"],
"run_at": "document_end" // Pay attention to this line
}
],
"manifest_version": 2
}
and content.js
:
和content.js
:
// alert("hello");
document.body.style.background = 'yellow';
Yes, that's enough.
And of course, don't forget to add an icon named icon.png
at the same directory with these two files, then test it in Google Chrome.
是的,这就够了。
当然,不要忘记icon.png
在这两个文件中添加同目录下的图标,然后在谷歌浏览器中测试。