简体   繁体   English

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

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

How can I write a simple Chrome Extension content script that will execute JavaScript (for example alert("hello"); ) on every page load?如何编写一个简单的 Chrome 扩展内容脚本,在每个页面加载时执行 JavaScript(例如alert("hello"); )?

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
}

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的图标,然后在谷歌浏览器中进行测试。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM