0

Is there a way to exclude one of the type of contextMenu if they overlapping?
example:
I have two context items, editable and selection.
In situation when both of those types match, (selection inside editable)

enter image description here

Chrome gives sub-menu for both actions.
I would like to have only one.
How can I prioritize or exclude one of those types in this specific situation?

2
  • 2
    Only one menu item is shown when you combine the two into one chrome.contextMenus.create call. Is that an option for you?
    – Rob W
    Nov 12, 2016 at 16:00
  • @RobW no, unfortunately I need different actions for those two. Only in situation when they overlap, I wanna make note to take priority prntscr.com/d6gc24
    – Wolf War
    Nov 12, 2016 at 19:41

1 Answer 1

1

If the menu item types are identical (i.e. same type, type, etc.), then you can declare the context menu and specify multiple contexts. Then the menu item will show up if any of the contexts match.

You've however stated that you really need separate context menu declarations:

  • Menu item with title "Make note" for the "selection" context.
  • Menu item with title "Insert note" for the "editable" context.
  • Menu item with title "Make note" when both contexts apply, e.g. when text is selected in an input field (so without the "Insert note" menu item).

The contextMenus API does not directly support this use case. So the next best alternative is to remove the context menu for the "editable" before the context menu appears in the third situation (and restore the context menu when the third situation is no longer relevant).

In your situation, I would use selectionchange to detect when the user (de)selects text. Upon selecting text, check whether an input field is in the selection (to do so you can combine the Selection, Range and/or DOM (traversal) APIs). If you find an input field, remove your desired context menu item. Regardless of whether you find a menu item, add listeners for key and/or mouse events to detect whether the user's pointer is on an input field.

Here is an example that uses selectionchange (https://stackoverflow.com/a/13673942/938089) and another one for Showing context menu buttons only when right-clicked on classes that start with “Story”.

1
  • Thank you Rob. I believe this is the only way to achieve it (and thus accepted answer), but is overkill for my needs. I will leave it as it is (with sub-menus version).
    – Wolf War
    Nov 13, 2016 at 12:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.