Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8920049
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T06:10:03+00:00 2026-06-15T06:10:03+00:00

I am trying to create entries on the Chrome context menu based on what

  • 0

I am trying to create entries on the Chrome context menu based on what is selected.
I found several questions about this on Stackoverflow, and for all of them the answer is: use a content script with a “mousedown” listener that looks at the current selection and creates the Context Menu.

I implemented this, but it does not always work. Sometimes all the log messages say that the context menu was modified as I wanted, but the context menu that appears is not updated.

Based on this I suspected it was a race condition: sometimes chrome starts rendering the context menu before the code ran completely.

I tried adding a eventListener to “contextmenu” and “mouseup”. The later triggers when the user selects the text with the mouse, so it changes the contextmenu much before it appears (even seconds). Even with this technique, I still see the same error happening!

This happens very often in Chrome 22.0.1229.94 (Mac), occasionally in Chromium 20.0.1132.47 (linux) and it did not happen in 2 minutes trying on Windows (Chrome 22.0.1229.94).

What is happening exactly? How can I fix that? Is there any other workaround?


Here is a simplified version of my code (not so simple because I am keeping the log messages):

manifest.json:

{
  "name": "Test",
  "version": "0.1",
  "permissions": ["contextMenus"],
  "content_scripts": [{
    "matches": ["http://*/*", "https://*/*"],
    "js": ["content_script.js"]
  }],
  "background": {
    "scripts": ["background.js"]
  },
  "manifest_version": 2
}

content_script.js

function loadContextMenu() {
  var selection = window.getSelection().toString().trim();
  chrome.extension.sendMessage({request: 'loadContextMenu', selection: selection}, function (response) {
    console.log('sendMessage callback');
  });
}

document.addEventListener('mousedown', function(event){
  if (event.button == 2) {
    loadContextMenu();
  }
}, true);

background.js

function SelectionType(str) {
  if (str.match("^[0-9]+$"))
    return "number";
  else if (str.match("^[a-z]+$"))
    return "lowercase string";
  else
    return "other";
}

chrome.extension.onMessage.addListener(function(msg, sender, sendResponse) {
  console.log("msg.request = " + msg.request);
  if (msg.request == "loadContextMenu") {
    var type = SelectionType(msg.selection);
    console.log("selection = " + msg.selection + ", type = " + type);
    if (type == "number" || type == "lowercase string") {
      console.log("Creating context menu with title = " + type);
      chrome.contextMenus.removeAll(function() {
        console.log("contextMenus.removeAll callback");
        chrome.contextMenus.create(
            {"title": type,
             "contexts": ["selection"],
             "onclick": function(info, tab) {alert(1);}},
            function() {
                console.log("ContextMenu.create callback! Error? " + chrome.extension.lastError);});
      });
    } else {
      console.log("Removing context menu")
      chrome.contextMenus.removeAll(function() {
          console.log("contextMenus.removeAll callback");
      });
    }
    console.log("handling message 'loadContextMenu' done.");
  }
  sendResponse({});
});
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-15T06:10:03+00:00Added an answer on June 15, 2026 at 6:10 am

    The contextMenus API is used to define context menu entries. It does not need to be called right before a context menu is opened. So, instead of creating the entries on the contextmenu event, use the selectionchange event to continuously update the contextmenu entry.

    I will show a simple example which just displays the selected text in the context menu entry, to show that the entries are synchronized well.

    Use this content script:

    document.addEventListener('selectionchange', function() {
        var selection = window.getSelection().toString().trim();
        chrome.runtime.sendMessage({
            request: 'updateContextMenu',
            selection: selection
        });
    });
    

    At the background, we’re going to create the contextmenu entry only once. After that, we update the contextmenu item (using the ID which we get from chrome.contextMenus.create).
    When the selection is empty, we remove the context menu entry if needed.

    // ID to manage the context menu entry
    var cmid;
    var cm_clickHandler = function(clickData, tab) {
        alert('Selected ' + clickData.selectionText + ' in ' + tab.url);
    };
    
    chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) {
        if (msg.request === 'updateContextMenu') {
            var type = msg.selection;
            if (type == '') {
                // Remove the context menu entry
                if (cmid != null) {
                    chrome.contextMenus.remove(cmid);
                    cmid = null; // Invalidate entry now to avoid race conditions
                } // else: No contextmenu ID, so nothing to remove
            } else { // Add/update context menu entry
                var options = {
                    title: type,
                    contexts: ['selection'],
                    onclick: cm_clickHandler
                };
                if (cmid != null) {
                    chrome.contextMenus.update(cmid, options);
                } else {
                    // Create new menu, and remember the ID
                    cmid = chrome.contextMenus.create(options);
                }
            }
        }
    });
    

    To keep this example simple, I assumed that there’s only one context menu entry. If you want to support more entries, create an array or hash to store the IDs.

    Tips

    • Optimization – To reduce the number of chrome.contextMenus API calls, cache the relevant values of the parameters. Then, use a simple === comparison to check whether the contextMenu item need to be created/updated.
    • Debugging – All chrome.contextMenus methods are asynchronous. To debug your code, pass a callback function to the .create, .remove or .update methods.
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to create a new entry in subversion for development. This is based
I am trying to create an iPhone application where the user can add entries.
Trying to create a background-image slideshow and am getting this error... This is the
I am trying to create a query which will check how many entries I
I'm trying to create a function that would add entries to a json file.
I'm trying to create a feature for my HTML/JavaScript timeline to sort the entries
I'm trying to create related articles for our news, based on tags (single word
I am trying to create a information based application, I have 92 subjects, for
I am very new to ruby and chef. I am trying to create entries
I'm trying to create a script to mess around with the db entries in

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.