Playing around with building a Chrome extension. At the moment I\'ve put together a context menu item. When the context menu item is clicked, it fires itemClicked()
You have probably misunderstood the concept of a background page (and its younger, more resource-friendly and preferred sibling: event page) and that of a content script.
content scripts:
background pages:
The chrome.contentMenus API is available only to a background page. Thus, you have to create any context menu and listen for onClicked
events there (in the background page).
Once a context menu has been clicked, you can use Programmatic Injection to inject some code (or a content script) into the active tab's web-page.
Below is the source code of a sample extension that demonstrates this method.
manifest.json:
{
"manifest_version": 2,
"name": "Test Extension",
"version": "0.0",
"background": {
"persistent": false, // <-- let's make it an event page
"scripts": ["background.js"]
},
"permissions": [
"contextMenus",
"activeTab" // <-- here, sufficient for our purpose
]
}
background.js:
/* Create a context-menu */
chrome.contextMenus.create({
id: "myContextMenu", // <-- mandatory with event-pages
title: "Click me",
contexts: ["all"]
});
/* Register a listener for the `onClicked` event */
chrome.contextMenus.onClicked.addListener(function(info, tab) {
if (tab) {
/* Create the code to be injected */
var code = [
'var d = document.createElement("div");',
'd.setAttribute("style", "'
+ 'background-color: red; '
+ 'width: 100px; '
+ 'height: 100px; '
+ 'position: fixed; '
+ 'top: 70px; '
+ 'left: 30px; '
+ 'z-index: 9999; '
+ '");',
'document.body.appendChild(d);'
].join("\n");
/* Inject the code into the current tab */
chrome.tabs.executeScript(tab.id, { code: code });
}
});
(If your injected code is complicated enough, it might be a better idea to inject a .js file. More info on Programmatic Injection.)