3 Understanding Chrome Extensions Content Scripts

Content scripts are a powerful feature of Chrome extensions that allow you to run JavaScript code in the context of web pages. This enables your extension to interact with web pages directly, modifying content, listening for events, and enhancing the browsing experience. Content scripts are specified in the manifest.json file and can be programmed to run on specific pages or across all pages. They operate in an isolated environment but can communicate with the rest of your extension through messaging. For a more comprehensive understanding of content scripts and how to implement them, refer to the official documentation provided by Google.

Thing of it this way, when a website is rendering in your browser it comes with its html, JavaScript and CSS files. Content scripts behave as if there are part of the files JavaScript and CSS files coming along with the website. So whatever you can do with JavaScript and CSS on your website, you can, virtually, do the same thing on an other person’s website.

There are 3 ways to declare content scripts in your extension, declared staticallydeclared dynamically, or programmatically injected., you can learn more here. In this article we will focus the declared statically option, as it is the most common way. The other two will be covered in a later article and both deal with the chrome.scripting api.

Below are examples of content scripts change the styles popular websites.

Setting up your extension.

If you have no idea how to setup files for a chrome extension please refer to an article we wrote about how to build you first chrome extension here. To include content scripts in your extension that field you include is your manifest.json file is content_scripts

Your file structure should look something like this.
{
"name": "Your Extension",
"version": "1.0.0.0",
"description": "Cool Description of your extension",
"manifest_version": 3,
"minimum_chrome_version": "88",
"content_scripts":[
{
"matches":["https://google.com"],
"js":["content.js"],
"css":["styles.css"],
"run_at": "document_end"
}
]
}

Core Concepts about statically declared content scripts

The content_scripts key in the manifest.jsonfile holds an array of objects that contain the following important fields

matches: An array of URLs patterns that your JavaScript and/or CSS files should run on. It is mandatory field. The * symbol is used as a wildcard to match all possible values. And <all_urls> matches any URL.

{
...,
"content_scripts":[
{
"matches":[
"https://www.google.com/",
"https://www.msn.com/",
"https://www.ebay.com/*",
"https://*.facebook.com/groups/*",
"*://*.amazon.com/",
],
"js":["content.js"],
"css":["styles.css"],
}
]
}

Note: if it you are just trying to match the base url for instance google.com, facebook, ebay.com make sure you include the https://subdomain at the beginning and a forward slash symbol / at the end. e.g https://www.google.com/, https://www.facebook.com/ or https://www.ebay.com/

js: This is an array of a list of JavaScript files that are going to run when the browser loads any of the pages in the matches section. You can have multiple content scripts and also put them in folders/directories run as well. Global variable are share between content scripts. Just remember when declaring content scripts in the manifest.json file it should be relative to the manifest.json file location.

{
...,
"content_scripts":[
{
"matches":["<all_urls>"],
"js":[
"./contentScriptFolder/helper.js",
"content.js"
],
}
]
}

css: This is an array of a list of CSS files that are going to run when the browser loads any of the pages in the matches section. This is optional. You can have multiple content scripts CSS files and also put them in folders/directories run as well.

{
...,
"content_scripts":[
{
"matches":["<all_urls>"],
"css":[
"./css/buttons.css",
"styles.css"
],
}
]
}

run_at: A string that specifies when the content scripts should run. This is optional. There are three options document_start, document_end or document_idle.

How do I use third party libraries in content scripts?

Let’s say you wanted to use JQuery or AlertifyJs libraries in your content scripts. Is that even possible? Yes!

You’ll have to download the javascript files, usually via cdn links, of the library you want to use and then add them into your local project and reference them like so;

{
...,
"content_scripts":[
{
"matches":["<all_urls>"],
"js":[
"./libs/jquery.js",
"./libs/alertify.js",
"content.js"
]
...
}
]
}

Please Note: Using the CDN link or external links to JavaScript files does not working in declaring content scripts. Content scripts have to be local

So NONE of this…

{
...,
"content_scripts":[
{
"matches":["<all_urls>"],
"js":[
"https://where-ever.com/jquery.js",
"https://myserver.com/content.js"
]
...
}
]
}

Extras on Content Scripts

There is more you can do with content scripts.

Photo by Caspar Camille Rubin on Unsplash

As mentioned before you the can virtual do everything with content script JavaScript files that normal web JavaScript allow you to do. Chrome extension have the ability special chrome APIs to enhance functionality. In the code snippet the content script. It will be web scrapping the page for h1 tags and collecting their text and saving them into chrome.storage.

// get all the h1 tags on the webpage
const h1s = document.querySelectorAll('h1');
const titles = [];

for(const h1 of h1s){
const title = h1.textContent;

//if title is not empty
if(title){
list.push(h1);
}

}

// save titles to chrome stroage.
chrome.storage.local.set({titles:titles});

Do not worry about what chrome.storage is if you are not aware of it. This snippet was just to show you the possibilities of content scripts and that they are more than just JavaScript files running on other people’s websites.

In conclusion, content scripts can be, if not, the core part of most extensions. Simulate button clicks, inserting text into input fields automatically, web scrapping. There are a number useful functions that content scripts are used for. The sky is the limit when it comes to the them.

Leave a Reply

Your email address will not be published. Required fields are marked *

More Articles & Posts