Uri
Uri

Reputation: 3291

How do I know which element was clicked in context menus?

We develop extensions for Chrome, Firefox and Safari. We want to add context menus to our extensions that will show when right clicking on any form element which is editable. I tried to add an editable context menu to Chrome:

chrome.contextMenus.create({
    "title": "Test editable menu item",
    "contexts": ["editable"],
    "onclick": function(info, tab) {
        console.log("item " + info.menuItemId + " was clicked");
        console.log("info: " + JSON.stringify(info));
        console.log("tab: " + JSON.stringify(tab));
    }
});

But I need to know which element the user clicked on, and info and tab don't contain the element. How do I know which element the user clicked? I would like to have a jQuery object containing the element.

The info object contains the following attributes:

"editable": true
"menuItemId"
"pageUrl"

Upvotes: 2

Views: 1793

Answers (2)

Alex Tircovnicu
Alex Tircovnicu

Reputation: 1

I know that is to late for you but I answer here for anyone else who's google it.

My solution was to create a mapping between created menu items and the business model (in this case a "data" array):

var itemsDic = {};
function onClickHandler(info) {
    alert(itemsDic[info.menuItemId]);
};

for(i in data) {
    var currentItem = chrome.contextMenus.create({
            parentId: item,
            title: data[i].ItemName,
            type: data[i].ItemType,
            contexts: ["editable"],
            onclick : onClickHandler
    });
    itemsDic[currentItem] = data[i];
}

Upvotes: -2

Antony Sargent
Antony Sargent

Reputation: 872

One of the best workarounds I know of is to follow the advice given in this thread to use content scripts to inject a listener in the target page for the 'contextmenu' event.

Upvotes: 3

Related Questions