在我阅读有关qazxsw poi的文档后,我没有获得使用Event Page而不是Background Page的优势。
假设我有以下简单案例 -
的manifest.json
Event Page
content.js
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
]
background.js
chrome.runtime.sendMessage("Hi Background")
在这种情况下,无论chrome.runtime.onMessage.addListener(messageListener);
function messageListener (request, sender, sendResponse) {
alert(request);
}
是persistent
还是"persistent": false
,"persistent": true
的听众总是应该醒来才能从background.js
获得消息,因此content.js
无法进入暂停模式。
那么事件页面(background.js
)在这种情况下和一般情况下的好处是什么?请举个例子。
事件页面的主要优点是通过在不使用时卸载后台脚本来释放RAM和CPU资源。
... background.js无法进入暂停模式。
它可以。即使您的事件页面使用了消息监听器,它仍会在一段时间后卸载。 Chrome会记住该页面已设置了侦听器,因此浏览器将在发送消息时唤醒该页面。
你可以试试这个实验:
的manifest.json
"persistent": true
background.js
{
"manifest_version": 2,
"name": "Test",
"version": "0.0.1",
"description": "",
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {
"default_popup": "popup.html"
}
}
popup.html
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
sendResponse({
msg: "it's alive!"
});
}
);
popup.js
<html>
<body>
<div id="text"></div>
<script src="popup.js"></script>
</body>
</html>