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 Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • DZone Community Awards 2022
  • Mastering Agile: Principles, Practices, and Real-World Insights
  • Beyond the Handoff: How Product and Engineering Teams Are Redefining Collaboration
  • Misunderstanding Agile: Bridging The Gap With A Kaizen Mindset

Trending

  • Why DDoS Protection Is an Architectural Decision for Developers
  • Is the Data Warehouse Dead? 3 Patterns From Enterprise Architecture That Answer This Question
  • Skills, Java 17, and Theme Accents
  • Data Contracts as the "Circuit Breaker" for Model Reliability
  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!

By 
Alan Richardson user avatar
Alan Richardson
·
Updated Mar. 07, 19 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
11.1K 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. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • DZone Community Awards 2022
  • Mastering Agile: Principles, Practices, and Real-World Insights
  • Beyond the Handoff: How Product and Engineering Teams Are Redefining Collaboration
  • Misunderstanding Agile: Bridging The Gap With A Kaizen Mindset

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook