How exactly does a Chrome event page work?

Deadly 提交于 2019-12-13 01:56:53

问题


From developer.chrome.com:

Chrome keeps track of events that an app or extension has added listeners for. When it dispatches such an event, the event page is loaded. Conversely, if the app or extension removes all of its listeners for an event by calling removeListener, Chrome will no longer load its event page for that event.

Because the listeners themselves only exist in the context of the event page, you must use addListener each time the event page loads; only doing so at runtime.onInstalled by itself is insufficient.

So I register a listener that only exists in the context of the event page, and then chrome loads the event page when that event occurs? How can it fire the listener if the page is currently unloaded and therefore the listener is undefined? And most importantly, how do I actually implement an event page?


回答1:


To implement an event page setup the background section of your manifest like this:

"background": {
    "scripts": [
        ...
        "/scripts/background.js"
    ],
    "persistent": false
},

"persistent": false makes it an event page.

In your background.js you will add listeners and functions like the following:

// event: display or focus options page
function onIconClicked() {
    bgUtils.showOptionsTab();
}

// event: process the state when someone has changed the storage
function onStorageChanged(event) {
    bgUtils.processState(event.key);
}

// listen for click on the icon
chrome.browserAction.onClicked.addListener(onIconClicked);

// listen for changes to the stored data
addEventListener('storage', onStorageChanged, false);

Chrome automagically takes care of the rest.

Two things to note:

DO NOT USE chrome.extension.getBackgroundPage() if you need access to the background page. USE chrome.runtime.getBackgroundPage() instead. It is asynchronous and makes sure the event page gets loaded.

You cannot have global variables in your event page. If you need to persist global state you need to use one of the storage API's.




回答2:


The answer to this, which puzzled me for a long time is, the listener is "cached" by Chrome, which basically means it is still defined just as normal. That "only in the context of the event page" just means that your page has to define it each time it runs, the first of which will be at runtime.onInstalled.



来源:https://stackoverflow.com/questions/36231029/how-exactly-does-a-chrome-event-page-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!