Chrome Extension - Part 2 ( Working with background.js and content-scripts )

Chrome Extension - Part 2 ( Working with background.js and content-scripts )

ยท

4 min read

So, in the previous article we saw how we can create a simple chrome extension using manifest.json file and some overview of how background.js file works and what it is? you can find that article here.

In this article we will try to add some basic functionality to our chrome extension using background.js and content-scripts. So, what is background.js file and content-scripts.

  1. Background.js - The file that runs when the chrome extension is installed and/ or updated to a newer version. You can basically consider it as a backend to your chrome extension.

Some examples where background.js comes into picture.

  • The background page listens for events.

  • It can communicate with content-scripts using message passing.

you can read more about it here .

  1. content-scripts - Content scripts are nothing but scripts that run in the context of underlying page. They can interact with the underlying webpage using DOM they can get details of the page as well as change css / inject a script.

you can read more about content-scripts here .

Okay enough of theory let's get into practicle in the previous article we setup a background.js file that just console logged a statement but in this article we will change the background color of the page using content-scripts and background.js file.

For using content-scripts you will have to add them into your manifest.json file.

first create a content-script named my-content-script.js or anything you wish to call it. By adding the content-script the folder structure would look like this

image.png

Now, that we have our content-script let's add it to our manifest.json file.

{
  "name": "My Cool Extension",
  "description": "This is the coolest extension",
  "version": "1.0",
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["my-content-script.js"]
    }
  ]
}

After adding the content-script the manifest.json file will look like above.

Here, matches takes in an array of url's that will have content-scripts injected automatically when we visit the page.

you can read more about it here.

After this save your manifest.json file and reload your extension present in chrome://extensions to check for any errors.

Now, to check if our content-script works we will try to console log something

console.log("My content script is running...");

Add the above line or anything you like in you content-script, reload your extension on a tab and go to any URL ( as we have given "" as the only parameter to "matches" it will work on any url ) and check the page's console you will see your console log from your content-script this means we have our content-script ready and working.

image.png

Now, this works automatically but you can also make it work by clicking on your extension icon for that let's visit background.js file.

So, you would add the below code to your background.js file

chrome.action.onClicked.addListener((tab) => {
  chrome.scripting.executeScript({
    target: { tabId: tab.id },
    files: ["my-content-script.js"],
  });
});

and also for using action api you need to add it in manifest.json file like below.

  "name": "My Cool Extension",
  "description": "This is the coolest extension",
  "version": "1.0",
  "manifest_version": 3,
  "permissions": ["activeTab", "scripting"],
  "background": {
    "service_worker": "background.js"
  },
  "action": {
    "default_icon": {
      "16": "/images/get_started16.png",
      "32": "/images/get_started32.png",
      "48": "/images/get_started48.png",
      "128": "/images/get_started128.png"
    }
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["my-content-script.js"]
    }
  ]
}

with addition to "default_icon" you can add a "default_popup" a html page. you can find the above icon's here this are chrome icons borrowed from chrome's website unzip them and add them in your extension folder after adding the icons your extension would look like this.

image.png

So, now as we are making the script to run when we click on the extension icon we will have to remove the "content-scripts" field from manifest.json file as it autoruns on all URLs and we want it to run only when clicked.

once you remove the "content-script" field from the manifest.json do the same procedure like above , reload the extension , open a page with any URL visit console and click on extension icon and you will see the console log from "content-script".

Now, time to change the background of the page we move to our content-script and add the following code.

document.body.style.backgroundColor = "orange";

After adding this one piece of code repeat the procedure load the extension, visit a URL , and click on your extension icon and voila the background color of the page changes.

And one more thing to add in this is when you use the command

chrome.scripting.executeScript

you will need to add "permissions" in manifest.json or else you will get an error.

image.png

and also for tab you will need permission so add "activeTab".

So, that's all for this article in the next part we will see how we can create popup page for our extension and a default script till then

๐ŸŽ‰๐ŸŽ‰๐ŸŽ‰๐ŸŽ‰ ๐ŸŽŠ๐ŸŽŠ๐ŸŽŠ๐ŸŽŠ๐ŸŽŠ ๐ŸŽ‰๐ŸŽ‰๐ŸŽ‰๐ŸŽ‰

Take Care ! and Keep Coding ๐Ÿง‘โ€๐Ÿ’ป