How to build Advance Chrome Extension.
Tags: tutorial, linkedi, extension, chrome
Published: 2022-12-15 14:31:56

Hii, This is Vaibhav Yadav, today We are going to learn how to build your Advance Chrome Extension.
We are going to learn how to build Linkedin Post liker and commenter, basically our extension will take Like count and Comment count from the Popup.html and after filling, it will show 'GO' button on below the input fields, after clicking the 'GO' button you will be redirected to your Linkedin Feed page where this Extension will Like and Comment "CFBR" on each Post.

Grab the repository here:- https://github.com/CaptainTron/Linkedin-Post-Liker-and-Commenter
Go to video : https://youtu.be/p-Up19eNgL4
Go to your Favorite Editor(like VS code)
Create a file name manifest.json and put below code

```
{
    "name": "Linkedin Post liker and Commenter", 
    "manifest_version": 3,
    "version": "1.0.0",
    "description": "This Is Advanced Web chrome extension that will count and post Comment 'CFBR' on each number of post you have given",
    "permissions": ["tabs"],
    "action": {   
      "default_popup": "pop.html", 
      "default_icon": {
        "16" : "Images/16.png",
        "32" : "Images/32.png",
        "48" : "Images/48.png",
        "128" : "Images/128.png"
      }
    },
    "content_scripts": [
      {
        "matches":["https://*.linkedin.com/*"],
        "js":["contentScripts.js"],
        "all_frames": true
      }
    ]

  }

```

so basically this is metadata of your Extension that will help browser to know about your Extension.
It contain self describing tags such as name, description, version, to tell the version of your extension(you can put whatever youwant bro!) and manifest version, this is important as it help to include the method and event for extension that help the extension to perform certain task such as change of tabs, internal messaging system, that we will cover here too!!,take note that permission is necessary to set 'tabs' without it we won't be able to access tabs of chrome, which necessary for interaction with website!!.
action will specity the action when someone click on the extension, here we specify the pop.html as default popup and default_icon as icon for our extension.
Content_script will has the ability to interact with DOM so take make our like and comment work we need, so here we go.
We have set it to contentscripts.js to denote the file we are using for contentscripts.
matches specify where we have to put our contentscript file into, here we have to specify the file we have to put for our contentscript file.

Next, Create pop.html and pop.js to structure the popup when someone click on your extension include the code given, it is using the same thing as we use to structure the html of any other website so no need to go there!
Code for pop.html
```
<!DOCTYPE html>
<html lang="en">
    <head>
        <!-- Link to font awesome !!! -->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w==" crossorigin="anonymous" referrerpolicy="no-referrer" />
        <style>
            /* Style of the style starts from here  I've put it here for better comprehension */
            body{
                width: 300px;
                background-color: rgb(27, 28, 29);
                border-radius: 3px;
                font-family: sans-serif;
                color: wheat;
            }
            button{
                background-color: rgb(24, 24, 20);
                border: none;
                cursor: pointer;
                padding: 6px;
                border-radius: 4px;
                margin: 6px;
                color: yellow;
                box-shadow: 0 0 5px wheat;
            }
            button:hover{
                background-color: rgb(56, 53, 45);
                color: wheat;
                box-shadow: 0 0 5px yellow,0 0 10px yellow;
            }
            input{
                width: 300px;
                margin: 8px 0  8px 0;
                height: 20px;
                border: none;
                border-radius: 5px;
            }
            input:focus[type="number"]{
                outline: none;
            }
            h3{
                margin: 0px;
            }
            .hidden{
                display: none;
            }
        </style>
    </head>
<body>
    <!-- body starts from here -->
    <!-- This element will take input from the user and passit to contentscript.js file using internalMessagesending system -->
    <div class="input">
        <!-- Taking input frim here -->
        <h3>Enter Like <i style="size: 500px;" class="fa-brands fa-linkedin"></i> Count:-</h3>
        <input type="number" class="cbtn"><br>
        <h3>Enter Comment <i style="size: 500px;" class="fa-brands fa-linkedin"></i> Count:-</h3>
        <input type="number" class="cmbtn">
        <!-- Once the user has successfully filled both the filled this button will show up here -->
        <div class="btn hidden" style="text-align: center;">
            <!-- Button will popup when user fill both input number only -->
            <button class="gobtn">GO</button>
        </div>
    </div>
    <script src="pop.js"></script>    
</body>
</html>
```
Code for pop.js

```
const like = document.querySelector('.cbtn');
const comment = document.querySelector('.cmbtn');
const btnv = document.querySelector('.btn');
const go = document.querySelector('.gobtn');

// adding add event listener method to listen for the keyup event and fire up the function that will execnute here:-
like.addEventListener('keyup',function(){
    // check wheather or not they are null 
    if(like.value!="" && comment.value!=""){
        // popup the button if condition match to true
        btnv.classList.remove('hidden');
    }else{
        btnv.classList.add('hidden')
    }
})
// This is for comment input field
comment.addEventListener('keyup',function(){
    if(like.value!="" && comment.value!=""){
        btnv.classList.remove('hidden');
    }else{
        btnv.classList.add('hidden');
    }
})
// this method will open the linkedin feed in the background of page and passs the data of Like count and comment count to contentscript.js using internal messaging system
go.addEventListener('click',function(){
    // grab the active tab and initialte the update method
    chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
        var tab = tabs[0]; 
        // this will open the tabs here;
        chrome.tabs.update(tab.id, {url: 'https://www.linkedin.com/feed/'});
        })
        // this method will pass the likecount and commentcount data to contentscript.js file
        chrome.runtime.onMessage.addListener(function (message, sender, sendResponse) {
            // this will print data incoming from contentscript.js file
            console.log(message)
            // this will send data
            sendResponse({
                data: like.value,
                data1: comment.value
            }); 
        });
    })
```

Next and final we have our most important things in our Extension that is Contentscript.js file that has ability to interact with DOM of webpage.
Below is the code for the same

```
(()  => {
    // creating variabls to store value so that it can be used for loops
        let likec,commentc,totalcount;
        // receiveing message and sending message form pop.js file
        chrome.runtime.sendMessage({
            data: "DataFectched Successfully"
             }, function (response) {
              console.log(response);
            //   parsing data to int so that it can be used as nummbers
              likec = parseInt(response.data);
              commentc = parseInt(response.data1)
            //   console loggint the data to browser page that si linkedin page
              console.log("Like count si " + likec);
              console.log("Comment Count is "+commentc);
            //   alert(totalcount);
            
        })
        // this is to check value at regular intervals
        let i=0,k=0;
                    // this function will print comment and like the button
                    // we have to make sure that DOM content has been successfully loaded and change is made thereafter otherwise it will show undefined error
                    // and also it will skip that part
                    // so that's why I've used timed interval to call and update value at intervals
                    function changehere() {
                            if(i<likec){
                                // this will grab the like button in the webpage and put it on like variable
                                let like = document.querySelector('.scaffold-finite-scroll__content').querySelectorAll('div .feed-shared-social-action-bar__action-button .react-button__trigger')[i]
                                // this will click that like button
                                like.click();
                                i++;
                              }
                                if(k<commentc){
                                  // this will first open the comment button
                                  let commentbtn = document.querySelector('.scaffold-finite-scroll__content').querySelectorAll('div .comment span div button')[k]
                                  commentbtn.click()
                                  // this will grab that input container from where we will input our data
                                  let comment = document.querySelector('.scaffold-finite-scroll__content').querySelectorAll('div .feed-shared-update-v2__comments-container .comments-comment-box .comments-comment-box__form-container .comments-comment-texteditor .comments-comment-box-comment__text-editor .editor-container .editor-content .ql-editor p')[k];
                                  // this will put data into that input field and ready to go
                                  comment.innerHTML="CFBR";
                                  // this will grab the post button where we must click to submit the our comment
                                  let post = document.querySelector('.scaffold-finite-scroll__content').querySelectorAll('div .social-details-social-activity .feed-shared-update-v2__comments-container .comments-comment-box .comments-comment-box__form-container form')[k].querySelectorAll('div button')[2]
                                  // this willl click on post button and will submit the task;
                                  post.click();
                                  k++;
                                }
                              }
                              // like.click();
                              // post.click();
                        // thsi method wil call changehere function again and again because it is timed event
                    setInterval(changehere, 4000);
                
})();

```
Note that we are using setInterval method to iterate in every 4 sec and like and comment, using for loop will go through once and if our webpage is not loaded successfully them it will throw undefined error and will not execute so it is important to be our page successfully loaded !!
Here we are listening from out pop.js file using internal messaging system that help us to talk to each other and help to share data.
Below is the code

```
chrome.runtime.sendMessage({
            data: "DataFectched Successfully"
             }, function (response) {
              console.log(response);
            //   parsing data to int so that it can be used as nummbers
              likec = parseInt(response.data);
              commentc = parseInt(response.data1)
            //   console loggint the data to browser page that si linkedin page
              console.log("Like count si " + likec);
              console.log("Comment Count is "+commentc);
            //   alert(totalcount);
            
        })
```

we are using the this method to hear response from the pop.js and send them also.
we are grabbing the data from function function and putting it to console and data using data, passing parameter!!.



that's all for now !!
Stay tuned for more such post!!.