shuboy2014 shuboy2014 - 4 months ago 51
Javascript Question

How can I add an option to the context menu dynamically in a Chrome extension?

I am making an extension in which the client generates some data in the extension and saves it in an array of objects in

localStorage
dynamically like:

var list = [{},{newly added object}];
localStorage.setItem("data", JSON.stringify(links));


When a client saves some data, I want to show the newly added object in the context menu of Chrome. If there are so many objects in an array, it's difficult for me to write this every time:

chrome.contextMenus.create({
id: "****",
title: "***",
contexts: ["all"]
});

chrome.contextMenus.onClicked.addListener(function(info, tab) {
if (info.menuItemId == "some-id") {
// do something
}

});


How can I do this? Any helpful suggestion will be appreciated.

Answer
  1. Every time you call localStorage.setItem, you could use something like Message Passing to tell background page it's time to update context menus. Then you could use chrome.contextMenus.create or chrome.contextMenus.update to update the context menu.

    chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
        chrome.contextMenus.create({
             id: "****",
             title: "***",
             contexts: ["all"]
        });
    });
    
  2. You could also save user data via chrome.storage.local.set, which is shared between content scripts and background page, then you could register event handler for chrome.storage.onChanged in backgorund page, and update the context menu inside the handler.

    chrome.storage.onChanged.addListener(function(changes, areaName) {
        chrome.contextMenus.create({
            id: "****",
            title: "***",
            contexts: ["all"]
        });
    });