Making a Browser Extension Tutorial

borwser extension popup demonstration
Share:

About

Over the years Google has been changing how their search results appear. For example, ads are harder to distinguish from real results, emojis, for some time they added icons, all sorts of widgets(“Top News”, “Twitter”, “People also ask”, …) appear instead of search results, … Some time ago when they made a few major changes further cluttering up the search results I decided I would make a browser extension that enables the user to customize and clean up the said mess.
You can find the source code here and you can download the extension for your browser here: ChromeFirefoxEdge.
In this post, I will share/document the things I have learned and show you how to make a basic extension yourself. Here is a list of the covered topics:

Make a Basic Extension

The first thing you need to do is make a folder and put a manifset.json file into it. For the web browser to recognize this as an extension you need to need to fill the file with the following JSON(Put the name and description you want for your extension.):

{
  "manifest_version": 2,

  "name": "My Extension",
  "description": "My first browser extension.",
  "version": "1"
}​

Open up your browser(Chrome in my case) go to the extensions(chrome://extensions/), click “Load unpacked” and select your extension folder containing the manifest.json file. The browser should now recognize your extension.

As you can see the extension was added to the web browser.

Adding An Icon

Next, let’s add some icons for our extension. First, you need to make some icons of course. They need to have the following sizes: 16×16, 48×48 and 128×128. I just used the logo of my blog and named the icons according to their sizes. Then put them into the extension directory.
Finally, we have to “declare” the icons in the manifest.json file like so:
{
  "manifest_version": 2,

  "name": "My Extension",
  "description": "My first browser extension.",
  "version": "1",
  "icons": {
    "128": "icon128.png",
    "48": "icon48.png",
    "16": "icon16.png"
  }
}
Now refresh the extension and you should be able to see the icons.

Adding a Popup For Our Extension

We have to “declare” our popup like so:
{
  "manifest_version": 2,

  "name": "My Extension",
  "description": "My first browser extension.",
  "version": "1",
  "icons": {
    "128": "icon128.png",
    "48": "icon48.png",
    "16": "icon16.png"
  },

  "browser_action": {
    "default_icon": "icon16.png",
    "default_popup": "popup.html"
  }
}

Now make a file named popup.html in the extension directory. Inside define the desired layout for your popup. I also added a style.css for the styling, popup.js for the code and linked to both files from the HTML file. I won’t go into detail about HTML, CSS and JS as I assume you already know how to work with them. 

This is just an example of the basic functionality. All the popup will do is take whatever you put in the text box and display it above it in the heading.

HTML:

​<!DOCTYPE html>

<html>
    <head>
        <title>Hello World</title>
        <link rel="stylesheet" type="text/css" href="style.css">
        <script src="popup.js"></script>
    </head>
    <body>
       <h1 id="headingText">Hello World!</h1>
       <input type="text" id="inputText">
    </body>
</html>

CSS:

h1{
   font-weight: bold;
   color: darkslategrey;
   text-decoration: underline; 
}
​

JS:

window.addEventListener('load', (event) => {

    document.getElementById("inputText").addEventListener("change", event =>{
        document.getElementById("headingText").innerHTML = event.target.value;
    });

});
​

Note:

A small tip, if you want to debug the code or manipulate the HTML for development purposes you can’t just open chrome developer tools by hitting F12 because it will open for the current web page you are on. Instead, you have to: open your popup, right click it and select inspect.

Run Code On The Current Web Page

If we want our extension to make changes or read from the current web page the user is on we have to include the code to do so. This can be done by adding a javascript file(I will name it code.js in this case.) to the extension directory and “declaring” it in the manifest.json like so:
{
  "manifest_version": 2,

  "name": "My Extension",
  "description": "My first browser extension.",
  "version": "1",
  "icons": {
    "128": "icon128.png",
    "48": "icon48.png",
    "16": "icon16.png"
  },

  "browser_action": {
    "default_icon": "icon16.png",
    "default_popup": "popup.html"
  },

  "content_scripts": [{
    "matches": [
      "<all_urls>"
    ],
    "js": ["code.js"]
  }]
  
}

You can use the matches array to define which URLs our script will be invoked on. In our case, all of them, see the documentation from Google if you want to know how to perform matching to some specific pattern.

The js array defines all the scripts that will get called when the URL matches.

 This simple bit of code here will get all the h2 elements and set their color to green. 

code.js:

window.addEventListener('load', (event) => {
    let list = document.getElementsByTagName("H2");

    for(let element of list){
        element.style.color = "green";
    }
});
Using a post on my blog as an example web page, all the h2 elements were turned green.

Popup and Web Page Script Communication

So far we have two different js scripts, one that is loaded when the extension popup is opened and one when the page gets loaded.

Here we’ll see how to send data from one to another. We’ll enter a color in the text box in the popup and send that to the script running on the web page to change all the h2 elements accordingly.

popup.js:

window.addEventListener('load', (event) => {

    document.getElementById("inputText").addEventListener("change", event =>{
        const color = event.target.value;
        document.getElementById("headingText").innerHTML = color;

        //Send color to web page in tab.
        chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
            chrome.tabs.sendMessage(tabs[0].id, color);
        });
    });

});

code.js:

window.addEventListener('load', (event) => {
    //When a message is received execute the receivedMessage function
    chrome.runtime.onMessage.addListener(receivedMessage);
});

function receivedMessage(message, sender, response){
    //When the message is received call and pass the value to the colorElements function.
    colorElements(message);
}

function colorElements(color){
    //Get elements.
    let list = document.getElementsByTagName("H2");
    //Color the elements.
    for(let element of list){
        element.style.color = color;
    }
}

Data Storage

In the previous section, we made it possible for the user to enter a color in the extension popup and get all the h2 elements on the web page colored accordingly. Here we will explore how to save that value in the browser and later retrieve it. This way the extension will automatically color the titles with the last entered color.
Again, we first need to modify the manifest.json file to enable storage. Like so:
{
  "manifest_version": 2,

  "name": "My Extension",
  "description": "My first browser extension.",
  "version": "1",
  "icons": {
    "128": "icon128.png",
    "48": "icon48.png",
    "16": "icon16.png"
  },

  "browser_action": {
    "default_icon": "icon16.png",
    "default_popup": "popup.html"
  },

  "content_scripts": [{
    "matches": [
      ""
    ],
    "js": ["code.js"]
  }],

  "permissions": [
    "storage"
  ]

}
And we’ll change our code like so:

popup.js:

window.addEventListener('load', (event) => {
    //Initialize extension to the stored values.
    chrome.storage.sync.get(['color'], function(color) { 
        setColor(color.color);
    });

    document.getElementById("inputText").addEventListener("change", event =>{
        //Get color.
        const color = event.target.value;
        //Set color.
        setColor(color);
        //Save color.
        chrome.storage.sync.set({'color': color}, function(){});
    });
});

function setColor(color)
{
    //Display the selected color.
    document.getElementById("headingText").innerHTML = color;
    //Send color to web page in tab.
    chrome.tabs.query({currentWindow: true, active: true}, function (tabs){
        chrome.tabs.sendMessage(tabs[0].id, color);
    });
}

code.js:

window.addEventListener('load', (event) => {
    //When a message is received execute the receivedMessage function
    chrome.runtime.onMessage.addListener(receivedMessage);

    chrome.storage.sync.get(['color'], function(color) { 
        colorElements(color.color);
    });
});

function receivedMessage(message, sender, response){
    //When the message is received call and pass the value to the colorElements function.
    colorElements(message);
}

function colorElements(color){
    //Get elements.
    let list = document.getElementsByTagName("H2");
    //Color the elements.
    for(let element of list){
        element.style.color = color;
    }
}

Well, this is it, you should now have the basic knowledge for making a browser extension. For any additional information see the documentation from Google. You can get the full code on Github.

Share:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger