在我阅读关于 Event Page 的文档之后我没有得到使用事件页面而不是背景页面的优势。
假设我有以下简单案例 -
list .json
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
]
content.js
chrome.runtime.sendMessage("Hi Background")
background.js
chrome.runtime.onMessage.addListener(messageListener);
function messageListener (request, sender, sendResponse) {
alert(request);
}
在这种情况下,persistent
是"persistent": false
还是"persistent": true
后台的监听器.js
始终应该处于唤醒状态,以便从 content.js
获取消息,因此 background.js
无法进入挂起模式。
那么事件页面 ("persistent": true
) 在这种情况下和一般情况下有什么好处?请举例说明。
最佳答案
事件页面的主要优点是在不使用时通过卸载后台脚本来释放 RAM 和 CPU 资源。
...background.js couldn't go to suspend mode.
可以。即使您的事件页面使用了消息监听器,它仍然会在一段时间后被卸载。 Chrome 会记住页面已经设置了监听器,因此浏览器会在发送消息时唤醒页面。
你可以试试这个实验:
- 添加此扩展
list .json
{
"manifest_version": 2,
"name": "Test",
"version": "0.0.1",
"description": "",
"background": {
"scripts": ["background.js"],
"persistent": false
},
"browser_action": {
"default_popup": "popup.html"
}
}
background.js
chrome.runtime.onMessage.addListener(
function(request, sender, sendResponse) {
sendResponse({
msg: "it's alive!"
});
}
);
popup.html
<html>
<body>
<div id="text"></div>
<script src="popup.js"></script>
</body>
</html>
popup.js
chrome.runtime.sendMessage('hello',
function (response) {
document.getElementById('text').textContent = response.msg;
}
);
- 打开 Chrome 的任务管理器并等待几秒钟,直到测试扩展程序消失(卸载)。如果您没有看到它(它已经卸载),您可以重新加载扩展。
- 单击扩展程序的浏览器操作,您将在窗口内看到来自事件页面的消息。此外,您可以在测试扩展的任务管理器中看到两个进程:一个是弹出窗口,第二个是事件页面。
弹窗关闭后,事件页面会在几秒后再次卸载。
关于javascript - 事件页面和背景页面的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45286794/