Context menus in Chrome extensions

Manifest v3 is out so to improve on Lucas Mendonca's answer, you just change the manifest.json to:

{
    "manifest_version": 3,
    "name": "App name",
    "version": "1.0",
    
    "permissions": ["contextMenus"],
    "background": { 
        "service_worker": "background.js",
        "persistent": false
    }
}

Script should look like this:

function getword(info,tab) {
  console.log("Word " + info.selectionText + " was clicked.");
  chrome.tabs.create({  
    url: "http://www.google.com/search?q=" + info.selectionText
  });
}
chrome.contextMenus.create({
  title: "Search: %s", 
  contexts:["selection"], 
  onclick: getword
});

And manifest.json:

{
    "name": "App name",
    "version": "1.0",
    "manifest_version": 2,
    "description": "Your description",
    "permissions": [
      "contextMenus"
     ],
    "background": { 
      "scripts": ["script.js"]
    }
}

Here you have how to load extension: http://developer.chrome.com/extensions/getstarted.html


The answer from Bartlomiej Szalach is too old. It will not work on Chrome Version 80.0.3987.163 (April 2020).

According to the documentation,

onclick: A function that is called back when the menu item is clicked. Event pages cannot use this; instead, they should register a listener for contextMenus.onClicked.

The background.js should be modified as follows:

const CONTEXT_MENU_ID = "MY_CONTEXT_MENU";
function getword(info,tab) {
  if (info.menuItemId !== CONTEXT_MENU_ID) {
    return;
  }
  console.log("Word " + info.selectionText + " was clicked.");
  chrome.tabs.create({  
    url: "http://www.google.com/search?q=" + info.selectionText
  });
}
chrome.contextMenus.create({
  title: "Search: %s", 
  contexts:["selection"], 
  id: CONTEXT_MENU_ID
});
chrome.contextMenus.onClicked.addListener(getword)

Improving on ahnquan's answer so chrome.contextMenus.create isn't called on every background script invocation, and also encoding the highlighted text into URI so it doesn't break when it contains special characters, such as ;,/?:@&=+$.

Your background.js will look like:

chrome.runtime.onInstalled.addListener(function() {
    chrome.contextMenus.create({
        "title": 'Search Google for "%s"',
        "contexts": ["selection"],
        "id": "myContextMenuId"
    });
});
    
chrome.contextMenus.onClicked.addListener(function(info, tab) {
    chrome.tabs.create({  
        url: "http://www.google.com/search?q=" + encodeURIComponent(info.selectionText)
    });
})

And manifest.json:

{
    "manifest_version": 2,
    "name": "App name",
    "version": "1.0",
    
    "permissions": ["contextMenus"],
    "background": { 
        "scripts": ["background.js"],
        "persistent": false
    }
}