Are you hiring developers for your company?

Others

How to Make a Chrome Extension

Posted in Others
How to Make a Chrome Extension

Google Chrome is the most used web browser today, and Chrome extensions are a great way to extend its functionality and add new features to it. Google has created comprehensive documentation which is enough for providing the basic information and gets the ball rolling, but as the complexity of the extension increases, we have to rely on third-party forums like Stackoverflow for help.

In this article, we will go through the process of creating an intermediate level chrome extension which will reduce the opacity of the video player controls on the youtube website, to increase the visibility of the content.

How to Make a Chrome Extension

This can be useful when you have paused the video, but the video player controls are hiding the content of the video behind them, such as some code of a programming tutorial.

Creating manifest.json file

The manifest.json file contains important information about the extension like its name, version, actions, and permissions. Every extension must have a manifest.json file. So let’s create a manifest.json file with the required fields in an empty directory:

{
"manifest_version": 2,
"name": "My First Extension",
"version": "0.1"
}

This creates a basic Chrome extension that does nothing other than loading the extension into Chrome. Keep in mind that the ‘manifest_version’ must always be 2, as version 1 is no longer supported starting from January 2014. Also, the manifest file must contain the three fields above.

Loading the extension into Chrome

To load the extension in Chrome, open up the chrome extensions page. To do that you can either click on the three dots on the upper right corner, then go to ‘more tools, and then ‘extensions’, or go to the address bar and type: “chrome://extensions/”. After that, turn on “developer mode” in the top right, and then click on “Load unpacked” in the top left. Now browse to the directory containing the manifest file, and then select that folder. The extension will now be displayed in the list below. After making any changes to the code, you can refresh the extension by clicking on the small refresh icon located on the right side of the extension.

Content Scripts

According to the official documentation, content scripts are files that run in the context of web pages. They can read or modify a web page, and pass information to their parent extension by utilizing the standard Document Object Model (DOM). The content script can exchange “messages” with their parent extension and therefore have the ability to access chrome APIs used by their parent extension. Some commonly used chrome APIs are: onConnect, onMessage and sendMessage among others.

Content scripts are completely isolated from the external environment, and this enables them to make changes to their own javascript environment without affecting the webpage or other content scripts.

To sum up, content scripts have the ability to access and modify the web page that the browser visits. This distinguishes them from other javascript files in the project. Content scripts have to be declared in the manifest file, along with their details, like which URL are they allowed to access.

Injecting Content Scripts

Content scripts can be injected into a webpage(s) in two ways programmatically or declaratively. In this example we use the programmatic injection as we only have to run the script on specific occasions. Before we inject the script, we have to first provide the active tab permission in the manifest, which enables the script to run on the currently active tab. If you want to automatically execute the content scripts on a new tab, you have to declare the content scripts in the manifest.

So we update the manifest.json file like this:

"permissions": ["activeTab"],
"content_scripts": [
{
"matches": ["https://www.youtube.com/*"],
"js": ["contentScript.js"]
}
]

Now we can inject the content script into the webpage. We can either inject a part of the code, or an entire file. In this example we will be injecting the entire javascript file, contentScript.js. When this file is injected, it will modify the youtube player window to reduce the opacity of the player controls. This file contains the following code:

//contentScript.js
var s = document.getElementById('stylehidecontrols');
if (s) {
s.remove();
}
else {
s = document.createElement('style');
s.id = 'stylehidecontrols';
var r = '#movie_player .ytp-gradient-top, #movie_player .ytp-gradient-bottom, #movie_player .ytp-chrome-top, #movie_player .ytp-progress-bar-container, #movie_player .ytp-chrome-controls{opacity: 0.2 !important;}';
s.appendChild(document.createTextNode(r));
document.body.appendChild(s);
}

First we try to find an element with id “stylehidecontrols”. If it is found, we remove it, to bring the opacity back to normal. If it is not found, then we have to reduce the opacity of the video player controls. To do that, we first create a “style” element to contain css style information, and assign it the id “stylehidecontrols”, which we were trying to find earlier. Now we create a text with CSS style information of various known elements in the youtube website which are associated with the video player, and assign it to a variable, “r”. Note that we have set the opacity for all these elements to 0.2, so that they are not obstructing the view, but still are visible and can be operated upon.

Now we create a node with the variable “r”, and then append it to the style element “s”. And finally we append “s” to the document body. This causes the new style to take effect immediately and reduces the opacity of the video controls. If the extension icon is clicked again, it will just remove the style element from the DOM, hence restoring the opacity to original.

Background Script

To inject the content script programmatically, we need javascript file which always runs in the background and listens for the click event. Content scripts have some limitations as they cannot listen to the click events, so we need a background script for this task which can access chrome API, but it can’t access the webpage. This background script listens to a specific event and then can inject javascript code into the page, which in turn can access and modify the webpage. We have to declare the background script file in the manifest like this:

"background": {
"scripts": ["backgroundScript.js"]
}

The background script is responsible for listening to the click event and then injecting the “contentScript.js” file into the page. The contents of the background script are:

//backgroundScript.js
chrome.browserAction.onClicked.addListener(
function(tab) {
chrome.tabs.executeScript(tab.id, {
"file": "contentScript.js"
});
});

In this example, we have directly injected the file into the page. We can also use message passing to achieve this task, where the background script will send a message to the content script on click event, and then the content script will listen for that specific message. If the message is received, it will execute the code.

Content scripts can also be injected “declaratively”. To do that, we can add something like this to the manifest.json file :

"content_scripts": [
{
"matches": ["http://*.mywebsite.com/*"],
"css": ["styles.css"],
"js": ["contentScript.js"]
}
]

The css field is optional and can be used to inject css files for the matching pages. They are injected in the order they are declared in the array.

Actions

Chrome extensions can have two types of actions, page actions and browser actions. Page actions can act only on the current page, unlike browser actions. We can include icons and popups for the extension using actions. To put an icon in the main Google Chrome toolbar, add this to the manifest.json file:

"browser_action": {
"default_icon": {
"32": "icon.png"
}
}

You can create icons of any size in an image editor like Photoshop, Illustrator, or Gimp. Also you can just download the icon of the required size form the internet. After you have the icon, place it with the current name in the root folder.

This adds a 32 by 32 size icon in the main toolbar of chrome. We can also include icons of other sizes, but If not provided, chrome will automatically resize the icon to fit accordingly.

The complete manifest.json file

After we add all the above fields in the manifest.json file, it will look like this:

//manifest.json
{
"manifest_version": 2,
"name": "Youtube Player Controls",
"version": "0.1",
"description": "This extension reduces the opacity of Youtube video player controls for better visibility of the content.",
"background": {
"scripts": ["backgroundScript.js"]
},
"permissions": ["activeTab"],
"content_scripts": [
{
//"matches": [""],
"matches": ["https://www.youtube.com/*"],
"js": ["contentScript.js"]
}
],
"browser_action": {
"default_icon": {
"32": "icon.png"
}
}
}

Directory Structure

The final directory structure is as below:

  • backgroundScript.js
  • contentScript.js
  • icon.png
  • manifest.json

For more information about Chrome extensions and how it works in the background, please visit the official documentation.

People are also reading:

Vikrant Singh

Vikrant Singh

Vikrant Singh is a Content Writer with 4 years of experience in web development as a full stack developer and content writer. He has worked with multiple technologies as a web developer and is proficient in many programming languages like Java, Javascript and c++, and frameworks like Node.js and React.js. He is committed to providing original and error free content for the web. View all posts by the Author

Leave a comment

Your email will not be published
Cancel