如何获取通过Google Chrome上下文菜单右键单击的元素? [英] How can I get the element that was right-clicked via a Google Chrome context menu?

查看:520
本文介绍了如何获取通过Google Chrome上下文菜单右键单击的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  chrome.contextMenus.create({
title:我的上下文菜单项,
contexts:[editable],
onclick:onClick
});

onClick 回调函数接收两个参数:一个 OnClickInfo 对象和一个选项卡对象。这两个对象都不包含对调用上下文菜单时右键单击的DOM元素的引用。我有 console.logged 这两个对象,但没有在任何地方看到对目标元素的任何引用。



所需的结果:


  • 用户右键点击一个可编辑的元素

  • 用户点击我的上下文菜单项在 onClick 回调中

  • ,我的扩展名搜索父目录form元素相对于目标右键元素
  • li>


现在看来,Chrome并没有提供任何对目标元素的引用。有没有人找到解决这个限制的方法?

解决方案

您必须在每个页面中注入内容脚本并监听 mousedown 事件并记录最后点击的元素。然后,当一个上下文菜单回调被调用时,你必须 sendRequest 到该标签来获取关于最后点击元素的信息。


I am creating a context menu item in Google chrome like so:

chrome.contextMenus.create({
 "title":"My Context Menu Item", 
 "contexts":["editable"], 
 "onclick": onClick
});

The onClick callback receives two arguments: an OnClickInfo object and a tab object. Neither object appears to contain a reference to the DOM element that was right-clicked when invoking the context menu. I have console.logged both of these objects but don't see any reference to the targeted element anywhere.

The desired outcome:

  • user right-clicks an editable element
  • user clicks my context menu item
  • within the onClick callback, have my extension search for a parent 'form' element relative to the targeted right-click element

As it stands right now, it doesn't look like Chrome offers any reference to the targeted element. Has anyone found a way around this limitation?

解决方案

You must inject a content script in each page and listen for mousedown event and log the last clicked element. Then, when a context menu callback is called you must sendRequest to the tab to get the info about that last clicked element.

这篇关于如何获取通过Google Chrome上下文菜单右键单击的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆