javascript Chrome 扩展中的后台脚本与内容脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12971869/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Background Scripts vs Content Scripts in Chrome Extensions
提问by Dark Light
I read about Background page and Content scripts at developer.chrome.combut I'm confused with them, I cannot understand when to use background scripts and when to use content scripts. For example:
我在developer.chrome.com 上阅读了有关后台页面和内容脚本的信息, 但我对它们感到困惑,我无法理解何时使用后台脚本以及何时使用内容脚本。例如:
manifest.json
:
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:
如果background.js
是:
// 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.
它运行良好,但如果我将上面相同的代码放入 中myScript.js
,它就不起作用了。
So I don't know which script should be located in background.js
, and which should be located in content scripts.
所以我不知道哪个脚本应该放在 中background.js
,哪些应该放在内容脚本中。
回答by The Alpha
Actually, Content scriptsare 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.
实际上,内容脚本是在网页上下文中运行的 JavaScript 文件。通过使用标准的文档对象模型 (DOM),他们可以读取浏览器访问的网页的详细信息,或对其进行更改。
A common need for extensions is to have a single long-running script to manage some task or state. Background pagesto 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.
对扩展的常见需求是拥有一个长期运行的脚本来管理某些任务或状态。后台页面进行救援。后台页面是在扩展进程中运行的 HTML 页面。它在扩展的整个生命周期内都存在,并且一次只有一个实例处于活动状态。