Unable to send message from context menu to content script

I want to send a message to the content script, when the user selects a context menu item. The content script will then, based on the message, format the webpage as required.

I was unable to do so and I have been able to locate the problem to the code responsible for sending the message (in the context menu script) or the one responsible for receiving message (in the content script). Below, I try to present a simplified version of the code that tries to duplicate the problem:

backgroundContextMenus.js:

chrome.runtime.onInstalled.addListener(function(){
    chrome.contextMenus.create({"title": "Testing",
                                "contexts": ["selection"],
                                "id": "testing"});
});
chrome.contextMenus.onClicked.addListener(function(info, tab){
    console.log("testing works");
    console.log("Before sending the bold message");
    chrome.tabs.sendMessage(tab.id, {changeParameter: "bold"});
    console.log("After sending the bold message");
});

markr.js:

chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse){
        console.log("Text toggled bold");
    }); 

Upon selecting the context menu item, the console shows these messages:

backgroundContextMenus.js:75 testing..
backgroundContextMenus.js:77 Before sending the bold message
backgroundContextMenus.js:79 After sending the bold message

So, as you may notice, there is no log saying “Text toggled bold”. Therefore, I suspect that there must be something wrong with the code responsible for sending message (chrome.tabs.sendMessage(tabs[0].id, {changeParameter: "bold"});)

I tried to follow this answer but it gives the same problem.

I am unable to figure out what exactly is wrong with it. It would be of great help if you could help me figure it out.

Open a new tab with xpath as search query

I am writing a chrome extension wich adds a context menu that when clicked opens a new google maps tab with a xpath value as search query.

xpath

//*[@id="component-1028"]/b

background.js

/* Create a context-menu */
chrome.contextMenus.create({
id: "GoogleMaps",   // <-- mandatory with event-pages
title: "Open On Google Maps",
contexts: ["all"]
});

/* Register a listener for the `onClicked` event */
chrome.contextMenus.onClicked.addListener(function(info, tab) {
if (tab) {
    /* Inject the code into the current tab */
    /* chrome.tabs.executeScript(tab.id, { code: code }); */
    chrome.tabs.executeScript(tab.id, {file: "content_script.js"});
}
});

content_script.js

window.open("http://maps.google.com/maps?q="+document.evaluate('//*[@id="component-1028"]/b', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.innerHTML;, '_blank');

But the content script doesn't seem to work with the document.evaluate added. But it works fine with something like this:

window.open("http://maps.google.com/maps?q="+, '_blank');

is it possible to add xpath value as a search query?

Thanks.

chrome.contextMenus.create with dynamic items

I want to build a chrome extension that has a menu with some items based on what you click on.

i use chrome.runtime.onConnectExternal to pass the date, everything works fine in here. but as the messaging between extension and site is done async some time the events come after the menu gets shown. and it dose not update after that.
the end result is that some times you see the menu based on the old item that was right clicked.

Is there a way to refresh the menu while open. or a way to comunicate between site and extension in a sync way?

Here is a example showing menu not updating:

const test = chrome.contextMenus.create({
    'title': `menu 0`,
    "contexts": ['all'],
});

let index = 0;

setInterval(() => {
    chrome.contextMenus.update(test, {title: 'menu ' + index++})
}, 1000);

Simple Chrome extension: Open image in CMS using file name in url

In my strides to make work more efficient for my colleagues I’m trying to make an extension that enables editors to open images directly from front end, a task our CMS can’t do.

The idea: When editors see an image they need to edit, they right-click and chose “Open in CMS”. The extension picks up the filename (including file extension) and opens a new url in our CMS.

Example:
Front end image url is http://www.justsomeurl.com/something/product.jpg

Image in the CSM can be accessed using search so that https://cms.justsomeurl.com/admin/appsomething/search:product.jpg

As a start I have tweaked an extension for Google Image search using this code:

function getClickHandler() {
  return function(info, tab) {

    var url = 'https://cms.justsomeurl.com/admin/appsomething/search:' + info.srcUrl;

    chrome.windows.create({ url: url, width: 1024, height: 870 });
  };
}

/**
 * Context menu.
 */
chrome.contextMenus.create({
  "title" : "Find image in CMS",
  "type" : "normal",
  "contexts" : ["image"],
  "onclick" : getClickHandler()
});

This of course sends the full url into the CMS search so it doesn’t work. I have tried to combine it with another script I found:

var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
alert(filename);

But since I basically have no idea what I’m doing it doesn’t work. Any help is greatly appreciated! Thanks!

Context Menu Extension using different queries based on selection

I want to write a Chrome/Opera Context menu Extension which uses different search queries for different selection using regex

chrome.contextMenus.create({
title: "Open: "%s" on Google Maps",
contexts: ["selection"],
onclick: searchText
});
function searchText(info){
var myQuery = encodeURI("https://maps.google.com/maps?q="+info.selectionText);
        chrome.tabs.create({url: myQuery});
}

I want to be able to use different queries if the selection text matches an IMEI for example and use another query if the text matches another regex

if(selection.match(/^[0-9]{15,15}|[,]$"/)) {
function searchText(info){
var myQuery = 
encodeURI("https://imeiquery.com/id="+info.selectionText);
        chrome.tabs.create({url: myQuery});
else if(selection.match(/^[0-9]{15,15}|[,]$"/)) {
function searchText(info){
var myQuery = encodeURI("https://maps.google.com/maps?q="+info.selectionText);
        chrome.tabs.create({url: myQuery});
}
}, true); 

The code above doesn’t really work. Is it possible?

Chrome Extension detect mouseover on context menu item

Is it possible to detect the mouseover event on the custom context menu item added with ‘chrome.contextMenus.create({…})’?

I want to kind of “preview” the action of the menu item when the user hovers their mouse over that menu item. So to do that I need to detect when the mouse is hovering over that item.

Is this possible?

Is it possible to listen to the “Copy Link Address” event in Chrome?

Chrome’s context menu offers a "Copy Link Address" option whenever you right-click on an appropriate element. I’m wondering if there’s an event that a listener can be added to in order to do things when a User performs that context menu action. I’ve tried all of the following to find the event, but none of these are triggered by the "Copy Link Address" action:

[
  'copy',
  'copyLink',
  'copy_Link',
  'copyAddress',
  'copy_Address',
  'copyLinkAddress',
  'copy_Link_Address'
].forEach(eventName => {

  addListener(eventName);

  const lowerCasedEventName = eventName.toLowerCase();
  if (eventName !== lowerCasedEventName) {
    addListener(lowerCasedEventName);
  }
});

function addListener(eventName) {
  document.addEventListener(eventName, function(e){
    console.log({eventName, e});
  }, true);
}

The “Copy” command is triggered by the copy listener, but none of these seem to be triggered by "Copy Link Address"

How to get the selected text to contextmenu title in chrome

Any idea how to get the selected text value to title field in chrome context menu item like google does with their context menu search here? window.getSelection() doesn’t seem to work.

here is an example of what I would like to implement

Chrome extension – right click to inspect element

I’m trying to implement some extension to inspect elements on the page. The first thought was to add a context menu like “Inspect element” but the information the callback is passing is not enough. Actually it doesn’t have any data about the element that is being right clicked. Is it possible at all? May be there are some other way to accomplish it?

The code I’m using is below:

function checkElement(info,tab) {
    // info doesn't have real information about the clicked object

  }
chrome.contextMenus.create({
    title: "Check element", 
    contexts:["all"], 
    onclick: checkElement,
  });

Thanks

Chrome extension: context menu icon not showing

I am building a Chrome extension and I set up a context menu which will show up and check the items (images or text) that the user selects from a table in the extension’s popup.

This is my code for creating the context menu in popup.js‘s window.onload:

chrome.contextMenus.removeAll();
chrome.contextMenus.create( {title: "Toggle Selected",
  documentUrlPatterns: [ "chrome-extension://*/popup.html"],
  contexts:["selection"], onclick: toggleselected} );

This is the function that gets called on the context menu’s onclick – also in popup.js (simplified version):

function toggleselected(info, tab)
    {
    var selection = window.getSelection(),
            q0 = document.querySelectorAll("[id^='id0']"),
            q1 = document.querySelectorAll("[id^='id1']");
    for (var i = 0; i < somearray.length; i++)
        {
        if (selection.containsNode(q1[i], true))
            {
            somearray[i].checked = !somearray[i].checked;
            q0[i].checked = !q0[i].checked;
            }
        }
    updatesomearrayinfo();
    }

And this is my manifest.json file (again, simplified version):

{
"manifest_version": 2,
"name": "Extension Name",
"version": "1.0",
"description": "Random description",
"browser_action":
    {
    "default_icon":
        {
        "16": "icon16.png",
        "32": "icon32.png",
        "48": "icon48.png",
        "128": "icon128.png"
        },
    "default_popup": "popup.html"
    },
"background":
    {
    "scripts": ["somescript.js"],
    "persistent": true
    },
"permissions": ["contextMenus", "tabs", "downloads", ""]
}

Everything works fine and the context menu correctly shows up when needed ... except that it doesn't have the extension's own icon next to it, but the default Chrome extension icon (the grey one). What can be done to correct this behavior? The icons in my manifest are ok, one of them (the 16x16 pixels, I believe) is correctly shown on my extension button, and apart from others usually doing the whole context menu thing from event pages, using chrome.runtime.onInstalled, contextMenus.onClicked.addListener and other listeners (which I am reluctant to use, since I specifically need to work with the variables from popup.js - e.g. somearray and queries on popup's elements), I don't seem to be doing anything different than things done by other extensions or the code samples in the answers here on StackOverflow. And they all get their own extension icons shown, apparently without doing anything special.

EDIT: Also, does anyone knows why the context menu for a selection is triggered only when the selection contains more than one specific item (an image, in my case)?