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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • DZone Community Awards 2022
  • Is Agile Right for Every Project? When To Use It and When To Avoid It
  • Breaking Bottlenecks: Applying the Theory of Constraints to Software Development
  • Enhancing Agile Software Development Through Effective Visual Content

Trending

  • Operational Principles, Architecture, Benefits, and Limitations of Artificial Intelligence Large Language Models
  • Next Evolution in Integration: Architecting With Intent Using Model Context Protocol
  • Building Reliable LLM-Powered Microservices With Kubernetes on AWS
  • Software Delivery at Scale: Centralized Jenkins Pipeline for Optimal Efficiency
  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
10.6K 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.

Related

  • DZone Community Awards 2022
  • Is Agile Right for Every Project? When To Use It and When To Avoid It
  • Breaking Bottlenecks: Applying the Theory of Constraints to Software Development
  • Enhancing Agile Software Development Through Effective Visual Content

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!