Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I restrict context menus to appear only for certain selected text in a Chrome extension?

I made a very simple chrome extension which allows users to highlight a DOI number, right-click and choose "Resolve DOI", and it sends them to the associated web page. Right now, this is done in background.html with:

chrome.contextMenus.create({
"title" : "Resolve DOI",
"type" : "normal",
"contexts" : ["selection"],
"onclick" : getClickHandler()
});

I would like to restrict the context menu option to only appear if the text they highlight begins with "10." Any suggestions on how to do this? Do I need to wait for the Context Menus module to become more advanced?

like image 842
MDMower Avatar asked Jan 19 '11 01:01

MDMower


People also ask

How do I create a context menu search?

To customize the extension, you will need to go to any website and copy a portion of text and then right click. One of the options you will see will be “Context Menu Search.” Click on this, and a menu will appear with some sites that the extension will automatically search for whatever text you have highlighted.

How do I disable Chrome Contextmenus?

Chrome context menu only apear on debugging app (loaded from a directory). But if you still want to disable context menu on your whole chrome app, simply use preventDefault() on the onContext event of your document... (every your custom context menu ll still work...)

Which actions displays the Windows context menu?

In Microsoft Windows, pressing the Application key or Shift+F10 opens a context menu for the region that has focus.


1 Answers

You would need to control content menu creation from a content script. Dynamic menu creation/deletion should execute pretty fast and the delay will be unnoticeable for a user.

  • Add mousedown event listener in a content script and check there whether selection satisfies your pattern.
  • Based on whether or not selection matches the patterrn, send a request to a background page asking to create or delete the menu.

Something along those lines (not tested):

content_script.js:

document.addEventListener("mousedown", function(event){
    var selection = window.getSelection().toString();
    if(selection.match(/^10\./)) {
        chrome.extension.sendRequest({cmd: "create_menu"});
    } else {
        chrome.extension.sendRequest({cmd: "delete_menu"});
    }
}, true); 

background.html:

chrome.extension.onRequest.addListener(function(request) {
    if(request.cmd == "create_menu") {
        chrome.contextMenus.removeAll(function() {
            chrome.contextMenus.create({
                "title" : "Resolve DOI",
                "type" : "normal",
                "contexts" : ["selection"],
                "onclick" : getClickHandler()
            });
        });
    } else if(request.cmd == "delete_menu") {
        chrome.contextMenus.removeAll();
    }
});
like image 98
serg Avatar answered Oct 03 '22 16:10

serg