Create Chrome Extension And Implement Basic Use Cases

Chrome extensions are developed using HTML, CSS, and JavaScript. Attached is the source code of one of the extensions, for a quick reference.
Below are the use cases which we will implement.
  • Create “Hello World” Chrome extension to display some HTML content in a pop-up.
  • Get URL of the currently browsed page when Chrome extension icon is clicked.
  • Get selected text from the currently browsed page to perform some actions.
  • Modify the current DOM element on which the Chrome extension is clicked.
To understand more, please read about the Chrome extension from this reference link.

‘Hello World’ Chrome Extension

  • Create a folder.
  • Create a file, name it ‘manifest.json”, and add the below code to it.
{  
  "name": "Hello World..",  
  "version": "1.0",  
  "description": "Trying first extension!",  
  "browser_action": {  
    "default_popup": "popup.html",  
    "default_icon": {  
      "16": "images/get_started16.png",  
      "32": "images/get_started32.png",  
      "48": "images/get_started48.png",  
      "128": "images/get_started128.png"  
    }  
  },  
  "icons": {  
    "16": "images/get_started16.png",  
    "32": "images/get_started32.png",  
    "48": "images/get_started48.png",  
    "128": "images/get_started128.png"  
  },  
  "manifest_version": 2  
}

 

Add the required icons in the images folder referenced in the above manifest.json file. Create the images folder under the same folder where manifest.json file is created.

Create a popup.html and add the following HTML code.
<!DOCTYPE html>  
<html>  
  <head>  
      
    <style>  
    body{  
   min-width:300px;  
   height:100px;  
   font-family: "Lucida Grande", Helvetica, Arial, sans-serif;  
     
   padding:10px;  
     
   }      
    </style>  
  </head>  
  <body>  
    <div style="background-color: DEEPSKYBLUE; height: 0px; margin-top: 0px"></div>  
     <p>Welcome To Hello World Chrome Extension</p>  
      
  </body>  
</html>

 

That’s it. We have our Chrome extension ready. Now, let us see how to load the extension. Extensions can be loaded in the unpacked mode by following the below steps.
  • Visit chrome://extensions (via omnibox or menu -> Tools -> Extensions).
  • Enable Developer mode by ticking the checkbox in the upper-right corner.
  • Click on the “Load unpacked extension…” button.
  • Select the directory containing your unpacked extension.
The above steps are only for development and testing purposes. For production usage, we have to publish the extension to the Chrome Extensions Store.
Below would be the expected output.

Now, let us modify the code to implement other 3 use cases. Below is the output which we are expecting.

We need to modify the files which we created above to implement other 3 use cases.
Below is the updated Manifest.json- if you notice, we have added permissions attribute. This tells the browser that the extension requires access to the mentioned resources.
{  
  "name": "Hello World..",  
  "version": "1.0",  
  "description": "Trying first extension!",  
  "permissions": ["activeTab", "declarativeContent", "storage","contextMenus"],  
  
  "browser_action": {  
    "default_popup": "popup.html",  
    "default_icon": {  
      "16": "images/get_started16.png",  
      "32": "images/get_started32.png",  
      "48": "images/get_started48.png",  
      "128": "images/get_started128.png"  
    }  
  },  
  "background": {  
    "scripts": ["contextmenu.js"]  
  },  
  "icons": {  
    "16": "images/get_started16.png",  
    "32": "images/get_started32.png",  
    "48": "images/get_started48.png",  
    "128": "images/get_started128.png"  
  },  
  "manifest_version": 2  
}

 

Popup.html
Added 3 buttons and the required HTML.
<!DOCTYPE html>  
<html>  
  <head>  
    <style>  
    body{  
   min-width:500px;  
   height:250px;  
   font-family: "Lucida Grande", Helvetica, Arial, sans-serif;  
    padding:10px;  
   }  
   </style>  
  </head>  
  <body>  
    <div style="background-color: DEEPSKYBLUE; height: 0px; margin-top: 0px"></div>  
     <p>Welcome To Hello World Chrome Extension</p>  
    <button id="GetURL"> Get Current URL</button>  
    <p > You are browsing URL -  <span id="url"> </span> </p>        
    <button id="getText"> Get Selected Text</button>  
    <p > Selected Text -  <span id="selectedtext"> </span> </p>  
    <button id="colorChange"> Change color of Page</button>       
    <script src="popup.js"></script>  
  </body>  
</html>

 

Popup.js 
'use strict';  
let GetURL = document.getElementById('GetURL');  
GetURL.onclick = function(element) {  
  getCurrentTabUrl();  
};  
document.getElementById('getText').onclick = function(element) {  
  chrome.tabs.executeScript( {  
  code: "window.getSelection().toString();"  
}, function(selection) {  
  document.getElementById("selectedtext").innerHTML = selection[0];  
});  
};  
function modifyDOM() {  
        //You can play with your DOM here or check URL against your regex  
        console.log('Tab script:');  
        console.log(document.body);  
        document.body.style.background = "blue"  
        return true;  
    }  
document.getElementById('colorChange').onclick = function(element) {  
  chrome.tabs.executeScript( {  
  code: '(' + modifyDOM + ')();' //argument here is a string but function.toString() returns function's code  
}, function(selection) {  
  alert(selection);  
});  
};  
function getCurrentTabUrl() {  
  var queryInfo = {  
    active: true,  
    currentWindow: true  
  };    
  chrome.tabs.query(queryInfo, (tabs) => {  
    var tab = tabs[0];  
    var url = tab.url;  
    document.getElementById('url').innerHTML = url;  
  });  
}

 

Step 1
Let us understand a few details about the code we are using to get the Current URL of the page being browsed.
We cannot directly bind on click event of buton, hence we are using onclick method of element to bind events.
let GetURL = document.getElementById('GetURL');  
GetURL.onclick = function(element) {  
  getCurrentTabUrl();  
};  
  
function getCurrentTabUrl() {  
  var queryInfo = {  
    active: true,  
    currentWindow: true  
  };    
  chrome.tabs.query(queryInfo, (tabs) => {  
    var tab = tabs[0];  
    var url = tab.url;  
    document.getElementById('url').innerHTML = url;   
  });  
}

 

Next thing is to query active tab which is done in getCurrentTabUrl method. Once we have tabs object, we are using 0th index of object to get url.
Step 2
Let us understand a few details about the code we are using for the current selected text. The below code again binds on click event handler on button on popup.html.
document.getElementById('getText').onclick = function(element) {  
  chrome.tabs.executeScript( {  
  code: "window.getSelection().toString();"  
}, function(selection) {  
  document.getElementById("selectedtext").innerHTML = selection[0];  
});  
};

 

Here we are using executeScript method to run some javascript code on the tab. Basically this gives us the flexility to run javascript code on the actual tab on which the chrome extension is being clicked.
  • So here we are using window.getSelections().toString() method to get the selected text
  • Then a plain javascript is used to render inside innerHTML of placeholder.
Step 3
Let us understand now, how to modify DOM element. The below code does DOM manipulation by changing backgroud color of page body element.
function modifyDOM() {  
        //You can play with your DOM here or check URL against your regex  
        document.body.style.background = "blue"  
        return true;  
    }  
document.getElementById('colorChange').onclick = function(element) {  
  chrome.tabs.executeScript( {  
  code: '(' + modifyDOM + ')();' //argument here is a string but function.toString() returns function's code  
}, function(selection) {  
  alert(selection);  
});  
};

 

  • Again here we are using exuecuteScript method to run some javascript code.
  • This code will give us document object of the active tab, as we wanted to execute more than one line of code inside the executeScript method. We are implementing a different method and using it as a string in code: parameter
  • We can play with our DOM inside this function like any normal JavaScript code.
Let us now see what happens when all things work together. As we have modified manifest.json file, make sure you go to extension and reload it. I am running the extension in current page scope (same page from where I am writing this article).
As you can see below,
  • Current URL is populated with CreateArticle.aspx page.
  • Selected Text is populated in the popup
  • The background color has changed to blue.

Conclusion

In this article, we have seen how to create a Chrome extension and implement a basic use case to access current browsed page resources like to get URL, selected text, and change the DOM of the page. Chrome extension is a very powerful handy tool which can enhance your user’s experience and let you create an extension specific to your application.

Note – This article was originally published at this link.

(Visited 5 times, 1 visits today)