Chrome 扩展上下文菜单,区分图像和 link 事件

Chrome Extension context menu, differentiate image and link event

在我的 chrome 扩展中,我添加了两个上下文项 "Get link" 和 "Get Image"。主要区别在于设置它们时,它们分别具有 link 和图像的 "context"。但是,当右键单击充当 link 的图像时,您可以选择两者:

当单击其中任何一个时,进入侦听器的数据似乎是相同的,我需要能够区分这两者以了解上下文是图像还是 link以不同的方式处理它们。这是我的代码:

chrome.runtime.onInstalled.addListener(function() {
  var context = "image";
  var title = "Copy Image";
  var id = chrome.contextMenus.create({"title": title, "contexts":[context],
                                         "id": "context" + context});  
});
chrome.runtime.onInstalled.addListener(function() {
  var context = "link";
  var title = "Copy link";
  var id = chrome.contextMenus.create({"title": title, "contexts":[context],
                                         "id": "context" + context});  
});
chrome.contextMenus.onClicked.addListener(onClickHandler);

function onClickHandler(info, tab) {
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
    chrome.tabs.sendMessage(tabs[0].id, {action: "imageAdded", subject: info.srcUrl}, function(response) {
});

看看 Parameter of onClicked callback,你可以通过 mediaType

区分 image/link

One of 'image', 'video', or 'audio' if the context menu was activated on one of these types of elements.

如果您想知道单击了哪个菜单项,可以在传递到 onClicked 处理程序:

function onClickHandler(info, tab) {
    console.log(info.menuItemId);
    //...
}