Let's take a look at an example of something I want to accomplish, which I have simplified for posting purposes. My goal is to add multiple context menu items that trigger the same function. Within this function, I want to be able to differentiate which item was clicked and respond accordingly.
In this particular example, I am adding two context menu items: one for shortening a link with bit.ly
and another for using tinyURL
.
chrome.contextMenus.create({'title': 'Shorten with bit.ly',
'contexts': ['all'],
'onclick': shortenLink});
chrome.contextMenus.create({'title': 'Shorten with tinyURL',
'contexts': ['all'],
'onclick': shortenLink});
The function that receives the input looks like this. By default, both info
and tab
are passed along with the request, but distinguishing which context menu item triggered the function may not be straightforward.
function shortenLink(info, tab){
}
Below is a console dump displaying those two variables:
https://i.sstatic.net/X7H5Z.png
While setting up separate functions for each item is an option, I have numerous context menu items to add. Given that they share many similarities in code, my preference is to have a single "dispatch" function that all items utilize. Is there a way to achieve this?
Edit
Possibly, I can determine which menu item triggered the function by utilizing the menuItemId
variable. Can I include additional information or data such as {method:'bitly'}
when calling the function?