How to Write a Chrome Extension From JavaScript Snippets Code [Video]
Let's take a look at how to write an extension for your Chrome browser!
Join the DZone community and get the full member experience.
Join For FreeWriting a Chrome Extension is pretty easy (getting it in the Chrome Store is much harder!). In this post, I will take the snippet code I wrote to generate CounterStrings and convert it into a Chrome Extension.
I have a video showing the full process at the bottom of the post. The text is basically a summary.
You can find the code for this Chrome Extension on GitHub.
CounterStrings Summary
A CounterString is a string like this *3*5*7*9*12*15*
where the *
represents the position in the string of the number immediately proceeding it.
- CounterString algorithms
- James Bach’s original writing and work on CounterStrings at satisfice.com
- Previous post implementing CounterStrings in JavaScript
A Manifest
First, we need to create a manifest.json
file.
This declares the name and version of the extension and links to the scripts being used. It is also where you declare the permissions that you need.
As you write your extensions, and you see which commands you are using, these will have the permissions required in the developer documentation.
Start with the basic manifest as documented in the Chrome tutorial and build it up as you add the code.
For example, I started with:
{
"manifest_version": 2,
"name": "Counterstring",
"version": "0.1",
"description": "simple counterstring generation"
}
And by the time I was finished it had become:
{
"manifest_version": 2,
"name": "Counterstring",
"version": "0.1",
"description": "simple counterstring generation",
"background": {
"persistent": true,
"scripts": ["js/background.js"]
},
"permissions": [
"contextMenus",
"activeTab"
],
"icons": {
"16": "icons/icon16x16.png",
"48": "icons/icon48x48.png",
"128": "icons/icon128x128.png"
}
}
Background.js
The background.js
file is where you’ll probably build most of your extensions.
I wanted to create the simplest extension I could think of and I thought having a right-click menu would be easiest. And that’s really all my extension does.
I used the documentation for context menus:
This told me to add the "contextMenus"
permission. Also, I defined the context menu to only appear when I right click on an editable web element "contexts" : ["editable"]
.
Because my CounterString is going to be added into that web element.
contextMenus.createCounterString =
chrome.contextMenus.create(
{"title":"Generate Counterstring",
"contexts" : ["editable"]
},
function (){
if(chrome.runtime.lastError){
console.error(chrome.runtime.lastError.message);
}
}
);
To handle clicks on the context menu I add a Listener.
chrome.contextMenus.onClicked.addListener(contextMenuHandler);
And then the function that handles the context menu click uses the chrome.tabs.executeScript
to inject some JavaScript into the active tab.
function contextMenuHandler(info, tab){
if(info.menuItemId===contextMenus.createCounterString){
chrome.tabs.executeScript({
file: 'js/counterstring.js'
});
}
}
counterstring.js
This is the exact code that I wrote as a snippet, but I saved it as a counterstring.js
file
function reverseString(reverseMe){
return reverseMe.split("").reverse().join("");
}
function getCounterString(count){
var counterString = "";
while(count>0){
var appendThis = "*" + reverseString(count.toString());
if(appendThis.length>count){
appendThis = appendThis.substring(0,count);
}
counterString = counterString + appendThis;
count = count - appendThis.length;
}
return reverseString(counterString);
}
var count = window.prompt("Counterstring Length?", "100");
var counterString = getCounterString(count);
console.log(counterString);
document.activeElement.value=counterString;
Persistent Background
In order to have my code injected, I needed to make the background.js
file persistent.
Icons
Chrome expects the extensions to have icons as described here:
You don’t actually have to do this when writing your extension, it helps, but you only really need it when you want to release to the Chrome store.
Running Your Extension From Code
In order to run your extension you have to:
- visit chrome://extensions.
- switch on Developer mode.
- click Load Unpacked.
- choose the extension folder (the one with the manifest.json in it).
Video
I’ve created a video showing this in action.
In the video, you will see the complete process and how to debug the extension when errors occur. This includes:
- how to convert existing JavaScript code into a Chrome Extension.
- the basic structure of an extension, manifest.json, background script, and content scripts.
- permissions in extensions: contextMenus, activeTab.
- how to create context menus for extensions.
- how to change where context menus are displayed: contexts, editable.
- why use a persistent background script.
- how to dynamically inject content scripts into a page using
executescript
. - how to use listeners with context menus.
Code
And you can find the source code on GitHub.
This article was syndicated from blog.eviltester.com. Author Alan Richardson is an Agile Software Development and Testing Consultant he has written 4+ books including Dear Evil Tester, Automating and Testing a REST API, Java For Testers. He has created 6+ online training courses covering Technical Web Testing, Selenium WebDriver and other topics. He is a prolific content creator on his blog, Youtube and Patreon.
Published at DZone with permission of Alan Richardson, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments