简体   繁体   English

单击菜单时触发事件

[英]Fire an event when menu is clicked

I'm working on a Chrome extension. 我正在使用Chrome扩展程序。 I've used chrome.contextMenus.create to create a menu item, and also passed in the function name to fire on click. 我使用chrome.contextMenus.create创建菜单项,并且还传入了函数名以在单击时触发。 Now what I want to do is, get the active link's textContent when I click on the context menu item. 现在我要做的是,单击上下文菜单项时获取活动链接的textContent。 What type and/or event should I listen to? 我应该听什么类型和/或事件? I don't know if textContent is even the correct thing. 我不知道textContent是否正确。 Let me try to describe: When you make a query on Google (let's say "putty" for the sake of example), the first hit is "PuTTY Download Page - Chiark" which points to some URL. 让我尝试描述一下:当您在Google上进行查询时(为方便起见,假设为“ putty”),第一个匹配项是“ PuTTY下载页面-Chiark”,它指向某个URL。 What I want to get is this "PuTTy Download Page - Chiark" rather than its URL. 我想要得到的是“ PuTTy下载页面-Chiark”,而不是其URL。

EDIT: This is what I have so far: 编辑:这是我到目前为止:

chrome.contextMenus.create({'title': 'Add to mySU bookmarks', 'contexts': ['link', 'page'], 'onclick': mySUBookmark});

function mySUBookmark() {
  var a = document.addEventListener('click', function() {
  ...
  });
}

I wonder if I'm in the right path. 我想知道我走的路是否正确。

Regards, mto 问候,MTO

Your click handler, is passed a contextMenusInternal.OnClickData info object , which has some properties of what was clicked (not the actual object itself). 您的点击处理程序会传递一个contextMenusInternal.OnClickData信息对象 ,该对象具有被点击内容的某些属性(而不是实际对象本身)。 For link elements this includes a linkUrl property, which you could use to create an element selector for the element, and pass this to your content script (which can access the page DOM). 对于链接元素,它包括一个linkUrl属性,您可以使用该属性创建该元素的元素选择器,并将其传递给您的内容脚本(可以访问页面DOM)。

This may be something like the below (you may need to change to work for your extension) 这可能类似于以下内容(您可能需要更改才能使用您的扩展程序)

function mySUBookmark(info, tab) {
   var elSelector = 'a[href="'+info.linkUrl+'"]';
   console.log(elSelector);
   // now send the selector to the content script on the page so it can use it
   // to select the element from the page DOM and do whatever you want with the
   // text / html of the element
   chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
      chrome.tabs.sendMessage(tabs[0].id, { elSel: elSelector }, function(resp) {});
   });
}

These links could help in understanding how all this stuff works, 这些链接可以帮助您了解所有这些东西的工作原理,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM