34

如何编写一个简单的 Chrome 扩展内容脚本来执行 JavaScript(例如alert("hello");在每次页面加载时执行 JavaScript(例如)?

因此,当我导航到页面或重新加载页面时,JavaScript 应该运行。

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
}
4

1 回答 1

69

如果您只需要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
}

content.js

// alert("hello");
document.body.style.background = 'yellow';

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

于 2013-10-13T16:55:04.023 回答