Laurent Laurent - 10 months ago 106
Javascript Question

How to retrieve the element where a contextmenu has been executed

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 ( but there is no progress since several months. Does someone knows a workaround: without jquery and/or with jquery?

Answer Source

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 =;
}, true);

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


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