Dan
Dan

Reputation: 16256

How to show the same context menu item under two conditions

I would like to show a menu item in the context menu if the user right-click on a selection OR they right click on an image.

Currently I am using this code but unfortunately it shows the menu item twice if I right click on an image which is part of a selection made by the user.

contextMenu.Item({
    label: contextMenuItemLabel,
    contentScriptFile: contextMenuItemContentScriptFiles,
    context: contextMenu.SelectionContext(),                
        onMessage: function (posted) { someFunction(posted) }               
});

contextMenu.Item({
    label: contextMenuItemLabel,
    contentScriptFile: contextMenuItemContentScriptFiles,
    context: contextMenu.SelectorContext("img"),
        onMessage: function (posted) { someFunction(posted) }
});

Can you please tell me what is the current way to do this if you know it - I am spending so much time on this.

Thanks.

Upvotes: 0

Views: 391

Answers (2)

Dan
Dan

Reputation: 16256

I went for this:

self.on("context", function (node, data) {
        return ((node.nodeName == "IMG") || 
                (getSelection().length) );
});

where getSelection() is a function returning the current selection.

Thanks for your help.

Upvotes: 0

Yansky
Yansky

Reputation: 4760

I'm not sure if there's an easier way to do it, but you could use the contentScript to find out if you're on an image element/node and/or if the user has selected text.

var cm = require("context-menu");
cm.Item({
  label: "dfhdfg",
  contentScript: 'self.on("context", function (node) {' +
                 '  if(node.nodeName==="IMG"){'+
                 '      //do something to web page or post a message back to addon  '+
                 '  } '+
                 '  else if(window.getSelection().toString()!===""){'+
                 '      //do something to web page or post a message back to addon  '+
                 '  } '+                 
                 '});'
});

Upvotes: 2

Related Questions