DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Culture and Methodologies
  3. Agile
  4. How to Write a Chrome Extension From JavaScript Snippets Code [Video]

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!

Alan Richardson user avatar by
Alan Richardson
·
Mar. 07, 19 · Tutorial
Like (2)
Save
Tweet
Share
8.88K Views

Join the DZone community and get the full member experience.

Join For Free

Writing 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.

  • developer.chrome.com/extensions/manifest

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:

  • developer.chrome.com/extensions/contextMenus

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.

  • About ExecuteScript
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:

  • developer.chrome.com/extensions/manifest/icons

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.


Watch on YouTube

Code

And you can find the source code on GitHub.

  • github.com/eviltester/counterstringjs


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.

JavaScript Snippet (programming) Software development Context menu agile

Published at DZone with permission of Alan Richardson, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Spring Boot vs Eclipse MicroProfile: Resident Set Size (RSS) and Time to First Request (TFR) Comparative
  • What Are the Benefits of Java Module With Example
  • Real-Time Analytics for IoT
  • How We Solved an OOM Issue in TiDB with GOMEMLIMIT

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: