如何检索已执行上下文菜单的元素

Lau*_*ent 34 javascript dom contextmenu google-chrome-extension

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

这是我的扩展的骨架:

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
    });
Run Code Online (Sandbox Code Playgroud)

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

ser*_*erg 52

您可以使用mousedown单击的事件侦听器和存储元素注入内容脚本:

内容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});
    }
});
Run Code Online (Sandbox Code Playgroud)

background.js

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

  • onRequest和sendRequest现已弃用.它应该是onMessage和sendMessage. (6认同)
  • 我收到“未检查的runtime.lastError:无法建立连接”。接收端不存在。` (5认同)
  • 甚至更好,[`contextmenu`事件](https://developer.mozilla.org/en/docs/Web/Events/contextmenu).在这种情况下,您不必检查`event.button == 2` (4认同)
  • 非常感谢.解决方案是使用内容脚本来检索和更改当前选项卡中包含的字段的内容.实际上,后台脚本是孤立的,无法访问当前网页的内容.然后,从内容脚本中可以使用document.activeElement (2认同)