Technical Article => Web => Web design

If you have experience of writing Chrome extension, you may be familiar with how you can add a context menu for your extension. The code would be similar to below:

chrome.runtime.onInstalled.addListener(function() { chrome.contextMenus.removeAll(); chrome.contextMenus.create({ "id": "your_id", "title": "Your Title", "contexts": ["all"] }); });

You need to add a listener listening to the extension install event. Once the extension is installed, create a context menu item with id your_id which applies to all elements on the page. After installing the extension, you would see the context menu shown when you right click on any part of the page.

The next time when Chrome is restarted, the context menu would still be there. This is somehow what you would expect.

Since Firefox claims that the code you write for Chrome can still work on Firefox, so it's very easy to port a Chrome extension to a Firefox extension with minimal change or even no change. The chrome object can still be accessed in Firefox though there is a correspondent in Firefox which is browser.

So you want to add a context menu to your Firefox extension and try to copy above code and run and you would find that the context menu is gone when next time the browser is restarted. It seems Firefox and Chrome are behaving differently on the onInstalled event.

To workaround the issue in Firefox, you should remove the onInstalled wrapper just put the context menu creation logic in the background.js and it will be ran every time when the browser starts.

chrome.contextMenus.removeAll(); chrome.contextMenus.create({ "id": "your_id", "title": "Your Title", "contexts": ["all"] });

There was a bug reported to Firefox some time back but it got resolved with reason WORKFORE which we are not sure how.

According to Chrome extension documentation. The below description is for onInstalled.

Fired when the extension is first installed, when the extension is updated to a new version, and when Chrome is updated to a new version.

It seems the onInstalled event would not be fired when browser restarted. This indicates that Chrome is behaving unexpected and maybe they will update it later. But another possibility is that the context menu creation is a one-time job which no need to be called every time the extension is loaded.

Hence suggestion for now is not wrapping context menu creation logic in a onInstalled listener.