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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:16:38  来源:igfitidea点击:

Chrome Extension - Simple Content Script for running js on any page

javascriptgoogle-chrome

提问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.jsonfile 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 helloon 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.pngat the same directory with these two files, then test it in Google Chrome.

是的,这就够了。
当然,不要忘记icon.png在这两个文件中添加同目录下的图标,然后在谷歌浏览器中测试。