How to retrieve the element where a contextmenu has been executed

做~自己de王妃 提交于 2019-11-26 09:23:28

问题


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.

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?


回答1:


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;
    });
}


来源:https://stackoverflow.com/questions/7703697/how-to-retrieve-the-element-where-a-contextmenu-has-been-executed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!