Build Your Own Chrome Extension

ยท

4 min read

Build Your Own Chrome Extension
Hello World! Lets Build an Chrome Extension

Extension is an supplementary window which helps in enhancing the user experience on web and most of the extensions are built using basic web technologies (html, css, javascript).

We are going to build a Clipboard Search Extension using some basic concepts of Javascript. Before starting with our build I would like to tell you about the extension which we are going to build.

Extension Name: Clipboard Search
  • This extension provide a way to user to use multiple search engine from one browser.
  • First User has to select the search engine (DuckDuckGo, Google, Bing, Ecoasia) form the select menu which will appear as a pop-up on the top-right corner of page.
  • After selecting the search engine user has to select a text on the web and then give copy(ctrl+c) task on that text.
  • Chrome extension will pass that selected and copied text as query to the url of search engine
  • Chrome extension will direct user to new active tab with the result.

Working Demo of Clipboard Search Extension

Let's Build This Extension ๐Ÿ‘

As far as folder structure is concerned the basic structure of any chrome extension would be as following:

  • manifest.json
  • index.html
  • index.js
  • style.css

Code Editor: VsCode

  1. manifest.json Create a file manifest.json and add the following code in it.
{
    "name": "Clipboard Search",
    "description": "Lets surf the web using our own Clipboard Search extension",
    "version": "0.1",
    "manifest_version": 2 ,

    "background": {
        "scripts": ["background.js"]
    },
    "browser_action": {
        "default_popup": "popup.html",
        "default_icon": "icon.png"
    },
    "permissions":[
        "tabs",
        "<all_urls>"
    ]
}

Hey!๐Ÿ™‹โ€โ™‚๏ธ that looks like some meta data right? Yes manifest.json contains all the meta data about our extension.

So what does this objects indicate

  • Name : name of the extension
  • Version: version of your extension
  • manifest version: for this extension project we are using version 2 of manifest and latest version in use is version 3.
  • permissions: these are the browser access required for our extension to work.
  • default_popup: it can be of popup type, modal type, or it can be directing the user to new page

after creating manifest.json we are going to add basic layout to our extension

popup.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="styles/popup_styles.css"></link>
</head>
<body>


        <div class="container">
            <div class="section1"> 
                <select name= "search_engine" id="search_engine">
                    <option value="" disabled selected>Choose a search engine</option>
                    <option value="google">Google</option>
                    <option value="startpage">Start Page</option>
                    <option value="duckduckgo">Duck Duck Go</option>
                    <option value="ecoasia">Ecoasia</option>
                    <option value="bing">Bing</option>
                </select>
                <button class="select-btn">Select</button>
            </div>

            <div class="section-2">
                <div class="search_engine_choice">Your Current Search Engine</div>
            </div>
        </div>

        <script src="scripts/popup_script.js"></script>
</body>
</html>

styles/popup_styles.css

.container{
    width: 400px;
    height: 200px;
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    align-items: center;
    background-color: #1e1e1e;
}


select, button {
    font-size: 20px;
}

.search_engine_choice{
    font-size: 30px;
    opacity: 0.3;
    color: wheat;
}

we have added basic layout and styling for chrome extension now let's deal with JavaScript Create the following script files.

  • scripts/foreground.js (here scripts is the folder which contains foreground.js and popup_script.js)
  • scripts/popup_script.js
  • background.js

background.js

let current_search_engine = '';

const search_engines = {
    google: 'https://www.google.com/search?q=',
    startpage: 'https://www.startpage.com/do/dsearch?query=',
    duckduckgo: 'https://www.duckduckgo.com/?q=',
    ecoasia: 'https://www.ecoasia.org/search?q=',
    bing: 'https://www.bing.com/search?q='
}

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab)=>{
    if(/^http/.test(tab.url) && changeInfo.status === 'complete'){
chrome.tabs.executeScript(tabId, {file: './scripts/foreground.js'}, ()=>{
    console.log("the foreground script has been injected.");
})
    }
})

chrome.runtime.onMessage.addListener((request, sender, sendResponse)=>{
    if(request.message === 'save_search_engine'){
        current_search_engine =  request.payload;
        // console.log(search_engines[current_search_engine]);
        sendResponse({message: 'success'});
    }else if(request.message === 'get_current_search_engine'){
        sendResponse({payload: current_search_engine});
    } else if(request.message === 'search'){
        chrome.tabs.create({
            active: true,
            url: `${search_engines[current_search_engine]}${request.payload}`
        })
    }
})

To understand the functionality of background.js we can divide the background.js in three sections

  1. It stores the url of search engines in object { }
  2. Checking the status of tabs and testing the url and then only the foreground.js script will be injected in background part of chrome extension.
  3. sending response on Message depending on the condition which is called by foreground and popup_script

popup_script.js

chrome.runtime.sendMessage({message: 'get_current_search_engine'}, response =>{
        document.querySelectorAll('option').forEach(option => {
            if(response.payload === option.value){
                document.querySelector('#search_engine').value = response.payload;
                document.querySelector('.search_engine_choice').style.opacity = 1;
                document.querySelector('.search_engine_choice').innerHTML = option.innerText;
            }
        })
});

document.querySelector('.select-btn').addEventListener('click', ()=>{
    document.querySelectorAll('option').forEach(option =>{
        if(option.selected){

            chrome.runtime.sendMessage({
                message: 'save_search_engine',
                payload: option.value
            }, response => {
                if(response.message === 'success'){
                    document.querySelector('.search_engine_choice').style.opacity = 1;
                    document.querySelector('.search_engine_choice').innerHTML  = option.innerText;

                }
            })
        }
    })
});

popup_script.js performs the following functions

  1. Selecting the value and passing the value to background.js
  2. Getting search engine value from background.js to display the user selected value in the popup
  3. save_search_engine value and get_search_engine value to and from background.js respectively.

foreground.js

document.addEventListener("copy", ()=>{
    navigator.clipboard.readText()
    .then(res=>{
        // alert(res);
        chrome.runtime.sendMessage({
            message: 'search',
            payload: `"${res}"`

        })
    })
    .catch(err=> console.log(err));
})

foreground.js keeps track of the copy operation performed on text or web element and send that copied element to background.js

On getting message from foregroud.js the background.js pass that selected text element as a query to the url of selected search engine and direct user to new active tab with the result for that selected text.

So let's load the extension on chrome browser

  • Go to "chrome://extensions" Screenshot (390).png

  • upload your chrome extension folder by selecting "load unpacked"

  • after uploading you can access your own extension from top-right corner of web page.

Screenshot (391).png

So this completes our chrome extension project ๐Ÿ™Œ๐Ÿš€

github code for reference: Github

ย