Google Chrome 扩展程序和上下文菜单:如何将一项功能用于多种用途?
这是我想要做的一个示例,为了在此处发布,它已被简化。我想添加几个实际上调用相同函数的上下文菜单项,然后在函数内部我希望能够区分调用了哪个菜单项并相应地对其进行操作。
此示例添加了两个上下文菜单项,一个用于缩短使用 bit.ly
的链接,另一个用于使用 tinyURL
。
chrome.contextMenus.create({'title': 'Shorten with bit.ly',
'contexts': ['all'],
'onclick': shortenLink});
chrome.contextMenus.create({'title': 'Shorten with tinyURL',
'contexts': ['all'],
'onclick': shortenLink});
接收函数看起来像这样,默认情况下 info
和 tab
都随请求一起发送,但我不认为我可以弄清楚调用了哪个上下文菜单函数就来自于此。
function shortenLink(info, tab){
}
这是这两个变量的控制台转储:
我知道我可以为每个项目设置单独的功能,但是我想要很多上下文菜单项添加和它们都共享很多相同的代码,所以我真的很想拥有一个它们都使用的“调度”函数。我怎样才能做到这一点?
编辑
也许我可以通过使用menuItemId
变量找出它是从哪个菜单项调用的,但是我可以传递一个附加参数或一些附加数据,例如{方法:'bitly'}
?
Here is an example of what I'd like to do, it's been simplified for the purpose of posting here. I'd like to add several context menu items which actually call the same function, and then inside the function I'd like to be able to differentiate which one was called and act upon it accordingly.
This example adds two context menu items, one for shortening a link with bit.ly
and one 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 receiving function looks something like this, and by default both info
and tab
are sent along with the request, but I don't think I can figure out which context menu called the function just from that.
function shortenLink(info, tab){
}
Here's a console dump of those two variables:
I know I can set up separate functions for each item, but there are a lot of context menu items I want to add and they all share a lot of the same code so I'd really like to just have one "dispatch" function that they all use. How can I do that?
Edit
Perhaps I can figure out what menu item it was called from by using the menuItemId
variable, but can I pass an additional parameter or some additional data such as {method:'bitly'}
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)