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.
  1. {  
  2.   "name""Hello World..",  
  3.   "version""1.0",  
  4.   "description""Trying first extension!",  
  5.   "browser_action": {  
  6.     "default_popup""popup.html",  
  7.     "default_icon": {  
  8.       "16""images/get_started16.png",  
  9.       "32""images/get_started32.png",  
  10.       "48""images/get_started48.png",  
  11.       "128""images/get_started128.png"  
  12.     }  
  13.   },  
  14.   "icons": {  
  15.     "16""images/get_started16.png",  
  16.     "32""images/get_started32.png",  
  17.     "48""images/get_started48.png",  
  18.     "128""images/get_started128.png"  
  19.   },  
  20.   "manifest_version": 2  
  21. }  
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.
  1. <!DOCTYPE html>  
  2. <html>  
  3.   <head>  
  4.       
  5.     <style>  
  6.     body{  
  7.    min-width:300px;  
  8.    height:100px;  
  9.    font-family: "Lucida Grande", Helvetica, Arial, sans-serif;  
  10.      
  11.    padding:10px;  
  12.      
  13.    }      
  14.     </style>  
  15.   </head>  
  16.   <body>  
  17.     <div style="background-color: DEEPSKYBLUE; height: 0px; margin-top: 0px"></div>  
  18.      <p>Welcome To Hello World Chrome Extension</p>  
  19.       
  20.   </body>  
  21. </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.
 
Create Chrome Extension And Implement Basic Use Cases
 
Now, let us modify the code to implement other 3 use cases. Below is the output which we are expecting. 
 
Create Chrome Extension And Implement Basic Use Cases
 
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.
  1. {  
  2.   "name""Hello World..",  
  3.   "version""1.0",  
  4.   "description""Trying first extension!",  
  5.   "permissions": ["activeTab""declarativeContent""storage","contextMenus"],  
  6.   
  7.   "browser_action": {  
  8.     "default_popup""popup.html",  
  9.     "default_icon": {  
  10.       "16""images/get_started16.png",  
  11.       "32""images/get_started32.png",  
  12.       "48""images/get_started48.png",  
  13.       "128""images/get_started128.png"  
  14.     }  
  15.   },  
  16.   "background": {  
  17.     "scripts": ["contextmenu.js"]  
  18.   },  
  19.   "icons": {  
  20.     "16""images/get_started16.png",  
  21.     "32""images/get_started32.png",  
  22.     "48""images/get_started48.png",  
  23.     "128""images/get_started128.png"  
  24.   },  
  25.   "manifest_version": 2  
  26. }  
Popup.html
 
Added 3 buttons and the required HTML. 
  1. <!DOCTYPE html>  
  2. <html>  
  3.   <head>  
  4.     <style>  
  5.     body{  
  6.    min-width:500px;  
  7.    height:250px;  
  8.    font-family: "Lucida Grande", Helvetica, Arial, sans-serif;  
  9.     padding:10px;  
  10.    }  
  11.    </style>  
  12.   </head>  
  13.   <body>  
  14.     <div style="background-color: DEEPSKYBLUE; height: 0px; margin-top: 0px"></div>  
  15.      <p>Welcome To Hello World Chrome Extension</p>  
  16.     <button id="GetURL"> Get Current URL</button>  
  17.     <p > You are browsing URL -  <span id="url"> </span> </p>        
  18.     <button id="getText"> Get Selected Text</button>  
  19.     <p > Selected Text -  <span id="selectedtext"> </span> </p>  
  20.     <button id="colorChange"> Change color of Page</button>       
  21.     <script src="popup.js"></script>  
  22.   </body>  
  23. </html>  
Popup.js 
  1. 'use strict';  
  2. let GetURL = document.getElementById('GetURL');  
  3. GetURL.onclick = function(element) {  
  4.   getCurrentTabUrl();  
  5. };  
  6. document.getElementById('getText').onclick = function(element) {  
  7.   chrome.tabs.executeScript( {  
  8.   code: "window.getSelection().toString();"  
  9. }, function(selection) {  
  10.   document.getElementById("selectedtext").innerHTML = selection[0];  
  11. });  
  12. };  
  13. function modifyDOM() {  
  14.         //You can play with your DOM here or check URL against your regex  
  15.         console.log('Tab script:');  
  16.         console.log(document.body);  
  17.         document.body.style.background = "blue"  
  18.         return true;  
  19.     }  
  20. document.getElementById('colorChange').onclick = function(element) {  
  21.   chrome.tabs.executeScript( {  
  22.   code: '(' + modifyDOM + ')();' //argument here is a string but function.toString() returns function's code  
  23. }, function(selection) {  
  24.   alert(selection);  
  25. });  
  26. };  
  27. function getCurrentTabUrl() {  
  28.   var queryInfo = {  
  29.     active: true,  
  30.     currentWindow: true  
  31.   };    
  32.   chrome.tabs.query(queryInfo, (tabs) => {  
  33.     var tab = tabs[0];  
  34.     var url = tab.url;  
  35.     document.getElementById('url').innerHTML = url;  
  36.   });  
  37. }  
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. 
  1. let GetURL = document.getElementById('GetURL');  
  2. GetURL.onclick = function(element) {  
  3.   getCurrentTabUrl();  
  4. };  
  5.   
  6. function getCurrentTabUrl() {  
  7.   var queryInfo = {  
  8.     active: true,  
  9.     currentWindow: true  
  10.   };    
  11.   chrome.tabs.query(queryInfo, (tabs) => {  
  12.     var tab = tabs[0];  
  13.     var url = tab.url;  
  14.     document.getElementById('url').innerHTML = url;   
  15.   });  
  16. }  
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.  
  1. document.getElementById('getText').onclick = function(element) {  
  2.   chrome.tabs.executeScript( {  
  3.   code: "window.getSelection().toString();"  
  4. }, function(selection) {  
  5.   document.getElementById("selectedtext").innerHTML = selection[0];  
  6. });  
  7. };  
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.
  1. function modifyDOM() {  
  2.         //You can play with your DOM here or check URL against your regex  
  3.         document.body.style.background = "blue"  
  4.         return true;  
  5.     }  
  6. document.getElementById('colorChange').onclick = function(element) {  
  7.   chrome.tabs.executeScript( {  
  8.   code: '(' + modifyDOM + ')();' //argument here is a string but function.toString() returns function's code  
  9. }, function(selection) {  
  10.   alert(selection);  
  11. });  
  12. };  
  • 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.  
Create Chrome Extension And Implement Basic Use Cases
 

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.


Similar Articles