Event pages and backward-compatibility
This section is only relevant if your extension supports Firefox 105 and earlier.
An extension designed as a non-persistent background page works even when event pages are not supported (i.e., in Firefox 105 and earlier) with one exception: the registration of context menus. In an event page, context menus persist across restarts, while they do not in persistent background pages.
If the recommendation to register menus in runtime.onInstalled
is followed, these menus are removed after a browser restart in Firefox 105 and earlier. To work around this issue, you could unconditionally call browser.contextMenus.create
. When the menu exists, the browser.runtime.lastError
property is set when the (optional) create
callback is called.
browser.contextMenus.create(
{
id: "my-menu",
},
() => {
}
);
If the initialization of the menu is expensive or requires complex logic, an alternative is to check whether event pages are supported and, if so, run the logic less frequently than at every wakeup of the event page (e.g., with runtime.onInstalled
or runtime.onStartup
).
You can detect the availability of event pages using the characteristic that an error is thrown synchronously when onclick
is passed to contextMenus.create
in an event page.
The following code shows how to use such a test to register menus.
let eventPagesSupported = true;
try {
browser.contextMenus.create({ id: "test-menu", onclick: () => {} });
eventPagesSupported = false;
browser.contextMenus.remove("test-menu");
} catch (err) {
}
async function registerMyMenus() {
browser.contextMenus.create({ id: "my-menu", });
}
if (eventPagesSupported) {
browser.runtime.onInstalled.addListener(registerMyMenus);
} else {
registerMyMenus();
}