Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

javascript - Background Scripts vs Content Scripts in Chrome Extensions

I read about Background page and Content scripts at developer.chrome.com but I'm confused with them, I cannot understand when to use background scripts and when to use content scripts. For example:

manifest.json:

{
    "name": "Hello World",
    "version": "2.0",
    "manifest_version": 2,
    "background": 
    {
        "scripts": ["background.js"]
    },
    "content_scripts":
    [
        {
            "matches": ["http://*/*", "https://*/*"],
            "js": ["js/myScript.js"]
        }
    ],
    "permissions": ["tabs", "http://*/*"],
    "browser_action":
    {
        "default_icon": "icon.png"
    }
}

If background.js is:

// Called when the user clicks on the browser action.
chrome.browserAction.onClicked.addListener(function(tab) {
  alert("test");
});

It works well, but if I put the same code above in myScript.js, it doesn't work.

So I don't know which script should be located in background.js, and which should be located in content scripts.

question from:https://stackoverflow.com/questions/12971869/background-scripts-vs-content-scripts-in-chrome-extensions

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Actually, Content scripts are JavaScript files that run in the context of web pages. By using the standard Document Object Model (DOM), they can read details of the web pages the browser visits, or make changes to them.

A common need for extensions is to have a single long-running script to manage some task or state. Background pages to the rescue.The background page is an HTML page that runs in the extension process. It exists for the lifetime of your extension, and only one instance of it at a time is active.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...