How to modify CSS of element that was right-clicked upon?

Hi, I’m a junior developer and I’ve been reading the documentation on how to create extensions.

I am now able to add a menu item to the context menu and once it is clicked, some CSS is adjusted using

browser.tabs.insertCSS({code: css});

This way I am able to change the look and feel of every occurence of a certain html element.

However, can somebody please tell me what I should do to change the CSS of the element that I right clicked upon to have the CSS apply only to that particular element?

At the moment, there isn’t a WebEXtension API to get the clicked element. There is a hack which is injecting a content script into every page to record the clicked element.

// hack: https://bugzilla.mozilla.org/show_bug.cgi?id=1325814
let clickedEl = null;
document.addEventListener('contextmenu', function(event) {
  clickedEl = event.target;
}, true);

Thanks, infortunately I don’t see where to integrate it in my code.

I currently have (just a sample project) in background.js:

browser.contextMenus.create({
id: “make-input-invisible”,
title: “Give this field a black background”,
contexts: [“editable”],
});

var css = “input[type=‘text’] {background-color: black; color: black;}”;

browser.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId == “make-input-invisible”) {
browser.tabs.insertCSS({code: css});
}
});

  • Create a content script
  • Add it to manifest.json to be injected into every page
  • Put the above code in it

Then from background script

let code =
  `clickedEl.style.backgroundColor='black';
   clickedEl.style.color='black';`;

browser.contextMenus.onClicked.addListener((info, tab) => {
  if (info.menuItemId === 'make-input-invisible') {
    broswer.tabs.executeScript({code}).then(onExecuted, onError);
    // onExecuted, onError : whatever you need to do with the result
  }
});

Awesome, thanks! Add-on is published to AMO here.