Chrome扩展程序 - 用于在任何页面上运行js的简单内容脚本

use*_*479 17 javascript google-chrome

Chrome扩展程序 - 内容脚本 - 如何编写一个简单的内容脚本,它将在每个页面加载时执行类似警报("hello")的javascript.我的意思是当我去google.com这样的网页时,应该会显示该消息.或者如果我重新加载任何页面,该消息应该出现在我的新视频中.请帮助.

我到目前为止有这个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
}
Run Code Online (Sandbox Code Playgroud)

yak*_*ang 50

如果您只需要hello在每个加载的页面上发出警报,下面是一个简单的演示:

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"
    },

    "content_scripts": [
        {
        "matches": [
            "http://*/*",
            "https://*/*"
            ],
        "js": ["content.js"],
        "run_at": "document_end"         // pay attention to this line
        }
    ], 
    "manifest_version":2
}
Run Code Online (Sandbox Code Playgroud)

以下是content.js:

// alert("hello");
document.body.style.background = 'yellow';
Run Code Online (Sandbox Code Playgroud)

是的,这就够了.
当然,不要忘记icon.png在这两个文件的同一目录中添加一个图标.
然后在你的chrome中测试它.

  • *content_scripts> matches*属性也支持*<all_urls>*,因此您不必为http,https等多种模式而烦恼.只需:`"匹配":["<all_urls>"],`这将匹配像`file:///`这样的东西. (2认同)