javascript 如何检索已执行上下文菜单的元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7703697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to retrieve the element where a contextmenu has been executed
提问by Laurent
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.
我正在尝试编写一个使用上下文菜单的 google chrome 扩展程序。此上下文菜单仅可用于可编辑元素(例如输入文本)。单击并执行上下文菜单时,我想在回调函数中检索已执行上下文菜单的元素(输入文本),以便更新与此输入文本关联的值。
Here is the skeleton of my extension:
这是我的扩展的骨架:
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
});
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?
与 mycallback 函数关联的参数不包含检索右键单击元素的有用信息。这似乎是一个已知问题 ( http://code.google.com/p/chromium/issues/detail?id=39507) 但几个月以来没有任何进展。有人知道解决方法:不使用 jquery 和/或使用 jquery?
回答by serg
You can inject content script with contextmenu
event listener and store element that was clicked:
您可以使用contextmenu
事件侦听器和存储被单击的元素注入内容脚本:
content script.js
内容脚本.js
//content script
var clickedEl = null;
document.addEventListener("contextmenu", function(event){
clickedEl = event.target;
}, true);
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if(request == "getClickedEl") {
sendResponse({value: clickedEl.value});
}
});
background.js
背景.js
//background
function mycallback(info, tab) {
chrome.tabs.sendMessage(tab.id, "getClickedEl", function(clickedEl) {
elt.value = clickedEl.value;
});
}