Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...