后台页面和后台脚本有什么区别? [英] What is the difference between background pages and background scripts?
问题描述
本文使用两个术语背景页" 和后台脚本"
我想到了背景脚本作为Manifest.json中的脚本的 background 字段
I think of background script as of background field with scripts in Manifest.json
但是背景页面是什么?它们之间有何不同?
But what is the background page and how they differ?
推荐答案
根据文档:
后台脚本是扩展程序的事件处理程序;它包含对扩展很重要的浏览器事件的侦听器.它处于休眠状态,直到触发一个事件然后执行所指示的逻辑为止.有效的后台脚本仅在需要时才加载,而在空闲时则不加载.
The background script is the extension's event handler; it contains listeners for browser events that are important to the extension. It lies dormant until an event is fired then performs the instructed logic. An effective background script is only loaded when it is needed and unloaded when it goes idle.
您可以使用background
清单条目中的persistent
键来配置后台脚本是否一直保持休眠状态直到需要为止或始终处于活动状态.例如:
You can configure if the background script remains dormant until needed or is always active with the persistent
key in the background
manifest entry. For example:
"background": {
"persistent": true,
"scripts": ["myBackground.js"]
}
如果您使用scripts
键(如上所述)声明背景脚本,Chrome将创建一个空 HTML页面,其中包含background
清单条目.因此,在上述情况下,Chrome会创建一个背景页面,例如:
If you declare your background scripts using the scripts
key (as above), Chrome will create an empty HTML page that includes the script(s) included in the script
key of the background
manifest entry. So in the case above, Chrome would create a background page like:
<html>
<head>
</head>
<body>
<script src="myBackground.js"></script>
</body>
</html>
如果您声明一个背景页面,则决定要包含在网页中的内容,并且必须在页面中包含脚本标签,因为您不能同时拥有page
和
If you declare a background page instead, you decide what to include in the webpage, and you have to include your script tags in the page, since you cannot have both page
and scripts
keys in the background
manifest entry.
声明背景页面的主要区别(和优点)是,您可以在其中包含任何想要的HTML元素.它们将不会显示(永远不会显示背景页面),但是它们的工作原理与其他任何页面一样.例如,在以下背景页面中,我添加了audio
标记,可在扩展程序运行时播放音乐:
The main difference (and advantage) of declaring a background page is that you can include whatever HTML elements you want in it. They will not be seen (background pages are never displayed), but they work as in any other webpage. For example, in the following background page I've included an audio
tag to play music while the extension is running:
manifest.json
"background": {
"persistent": true,
"page": "myBackgroundPage.html"
}
myBackgroundPage.html
<html>
<body>
<audio id="mySong" src="mySong.mp3" autoplay loop></audio>
<script src="myBackground.js"></script>
</body>
</html>
仅使用脚本并包含类似以下内容即可达到相同的结果:
You could have achieved the same result using only a script and including in it something like:
var myAudio = document.createElement('audio');
myAudio.src = 'mySong.mp3';
myAudio.autoplay = true;
myAudio.loop = true;
document.body.appendChild(myAudio);
但是在这种情况下,我认为创建自己的背景页面更加方便.
but in cases like this I think that creating your own background page is more convenient.
这篇关于后台页面和后台脚本有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!