Intro π¨
Alright so following our last article we were able to create a simple chrome extension. Today we're going to be adding a context menu that pops up an alert whenever we right click on an a page, so let's get started.
Details π
In chrome extension there are two types of pages; background and event pages. Now, background pages are ones that are always running code an example is good'ol adblocker π while event pages run when required/called. For this article we will create an event page.
- Adding the event page
To create our event page we add the following to our manifest.json:
{
"manifest_version": 2,
"name": "My App Extension",
"description": "A basic chrome extension of react app. nothing too tedious",
"version": "0.1",
"browser_action": {
"default_popup": "index.html",
"default_title": "Open the popup"
},
"icons": {
"192": "logo192.png",
"512": "logo512.png"
},
"content_security_policy": "script-src 'self' 'sha256-xxxxxxx'",
"background": {
"scripts": ["eventPage.js"],
"persistent": false
},
"permissions": [
"contextMenus"
]
}
From the above there have been some additions;
background: which has the script file for our context page and persistent that determines if the script is a background or event page ( false = event, true = background).
permissions: allowing our chrome extension to create a context menu.
- Defining our context menu:
In the same directory as our manifest create a file with what was previously entered as the script value in background, in this case eventPage.js, now add the following to that file:
var contextMenuItem ={
"id": "tutorial02",
"title": "My Chrome context menu π", /* what appears in the menu */
"contexts": ['page'] /* to make this appear only when user selects something on page */
}
chrome.contextMenus.create(contextMenuItem);
chrome.contextMenus.onClicked.addListener( (clickData) => {
if(clickData.menuItemId == "tutorial02"){
alert("clicked point in page ππ")
}
})
From the above, the variable *contextMenuItem * defines our context menu. An id as an identifier, title for what we see when we right click and contexts for what causes the context appear(page means action in the current page).
chrome.contextMenus.create creates the context menu with our item.
chrome.contextMenus.onClicked.addListener adds the functionality of when the menu is clicked an alert is popped up.
- Build our extension
Now npm run build the project and reload our extension from chrome://extensions and all what we did is applied. You should have this when you right click on your page:
And when clicked:
Conclusion π
And with that you have added a context menu to your extension, π π
Top comments (0)