如何检索已经执行上下文菜单的元素 [英] How to retrieve the element where a contextmenu has been executed

查看:114
本文介绍了如何检索已经执行上下文菜单的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用上下文菜单编写一个Google Chrome扩展。此上下文菜单仅适用于可编辑元素(例如输入文本)。当上下文菜单被单击并执行时,我想在回调函数中检索已经执行了上下文菜单的元素(输入文本),以更新与此输入文本相关联的值。

I am trying to write a google chrome extension where I use a contextmenu. This contextmenu is available on editable elements only (input texts for example). When the contextmenu is clicked and executed I would like to retrieve in the callback function the element (the input text) on which the contextmenu has been executed in order to update the value associated to this input text.

这是我的扩展的骨架:

function mycallback(info, tab) {
  // missing part that refers to the question:
  // how to retrieve elt which is assumed to be 
  // the element on which the contextMenu has been executed ?
  elt.value = "my new value"
}

var id = chrome.contextMenus.create({
        "title": "Click me",
        "contexts": ["editable"],
        "onclick": mycallback
    });

与mycallback函数关联的参数不包含检索右键元素的有用信息。看来这是一个已知问题( http://code.google.com / p / chromium / issues / detail?id = 39507 ),但几个月后没有进展。有人知道解决方法:没有jquery和/或使用jquery?

The parameters associated to the mycallback function contain no useful information to retrieve the right clicked element. It seems this is a known issue (http://code.google.com/p/chromium/issues/detail?id=39507) but there is no progress since several months. Does someone knows a workaround: without jquery and/or with jquery?

推荐答案

您可以使用 mousedown 事件侦听器和被点击的存储元素:

You can inject content script with mousedown event listener and store element that was clicked:

content script.js

//content script
var clickedEl = null;

document.addEventListener("mousedown", function(event){
    //right click
    if(event.button == 2) { 
        clickedEl = event.target;
    }
}, true);

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if(request == "getClickedEl") {
        sendResponse({value: clickedEl.value});
    }
});






background.js

//background
function mycallback(info, tab) {
    chrome.tabs.sendMessage(tab.id, "getClickedEl", function(clickedEl) {
        elt.value = clickedEl.value;
    });
}

这篇关于如何检索已经执行上下文菜单的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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