事件页面和背景页面之间的差异

问题描述 投票:1回答:1

在我阅读有关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)在这种情况下和一般情况下的好处是什么?请举个例子。

javascript google-chrome google-chrome-extension
1个回答
4
投票

事件页面的主要优点是通过在不使用时卸载后台脚本来释放RAM和CPU资源。

... background.js无法进入暂停模式。

它可以。即使您的事件页面使用了消息监听器,它仍会在一段时间后卸载。 Chrome会记住该页面已设置了侦听器,因此浏览器将在发送消息时唤醒该页面。

你可以试试这个实验:

  1. 添加此扩展程序

的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>
  1. 打开Chrome的任务管理器并等待几秒钟,直到测试扩展程序消失(卸载)。如果您没有看到它(它已经卸载),您可以重新加载扩展。
  2. 单击扩展程序的浏览器操作,您将在窗口中看到来自事件页面的消息。此外,您可以在任务管理器中看到测试扩展的两个进程:一个是弹出窗口,第二个是事件页面。 弹出窗口关闭后,事件页面会在几秒钟后再次卸载。
© www.soinside.com 2019 - 2024. All rights reserved.