Chrome Extensions in React

Yash Garudkar
7 min readJul 4, 2021

Chrome extensions are small programs that act as an addition to the Google Chrome Browser that enables the user to use additional capabilities. Some notable chrome extensions are Grammarly, Amazon Assistant and Honey.

Photo by Paul Hanaoka on Unsplash

Lately, Chrome extensions are really garnering good attention for the tasks they do and automate. They are powerful tools for companies to reach the customer without having to open their webpage.

Extensions can be an excellent way of staying connected to the user via niche product feature, whenever a user is using the browser. Lately, the chrome extensions have skyrocketed the sales for many companies and also helped new startups.

React is a JavaScript library that can be used to build anything from mobile apps to websites, PWAs. The library is known for its ability to create beautiful user interfaces and the reusability of components.

Let us explore how we can create an extension using react and see how we can build a starter todo app on our own.

There are many ways you can create a react-chome extension. I am going to use create-react-extension because it's faster and gets the project bootstrapped right away.

How does a Chrome Extension work?

Chrome Provides developer APIs for reference. These APIs extend our code to use features that help us do numerous things with the extensions.

In a chrome extension there are mainly two scripts that will help us to build and use our features, namely:
1. Background script — the browser script runs in the background of the extension, it is mainly the script that will be used if we don’t want to communicate with the website and their data.
2. Content script — the content script is injected into the website as the logic specifies. You can manage a specific website that matches your regex and then injects the content script accordingly.

What if I want to communicate with the webpage and use some data from a webpage in the extension?

This is where we use the contentScript and backgroundScript to call certain API functions that allow us to communicate with each other.

  1. Both the content and the background scripts will be assigned, specific event listeners.
  2. The user will perform an action that will invoke an event that will dispatch a message to the contentScript.
  3. Based on the message the content script will carry out the assigned event function and finally invoke an event function that will dispatch a message to the background script.

Once a backgroundScript is loaded it stays running until it is acting. This action may be an event, that an event listener is will catch in the contentScript that depends on some data that the content script will return.
for eg:

chrome.runtime.onMessage.addListener(listener: function)

What are we going to build?

We will build a to-do app in React that can be used on the Chrome browser. This process will use the chrome.storage API to store and sync our tasks between browsers that we have logged into.

1. Design the UI for the extension:

I designed this UI in Figma, I kept it simple but feel free to add custom elements for your design!

The image contains header named TaDa and input elements namely input, select element to specify priority of the task and a submit button to add the task. Below the elements two tasks and each of them have a delete button assigned to each of it.
UI design for the app

2. Create a new project:

We will use create-react-extension as discussed above please make sure you have node and npm installed. Use the following command to create a new react-extension project:

npx create-react-app todo-extension --scripts-version react-browser-extension-scripts --template browser-extension

The todo extension as highlighted above is the name for our project, feel free to change the name as you would like it.

3. Project structure:

  1. The public folder: this folder contains the index.html file that is the root of our application. And other files that will help us run our chrome extension.
  2. manifest.json: This is the entry file of the chrome extension we will discuss more of this in the next segment.
  3. src folder: src will hold the App.js file where we will make main changes for the UI and perform our logic.
  4. background folder: here you can write the script for running in the background for the chrome extension as we discussed earlier.
  5. contentScript folder: here you can write scripts that need to be injected into the current webpage.

4. Updating the manifest.json

The manifest.json is the entry file for any extension. It contains important information and enabled us to add and remove features for our app.

In the manifest.json you will see a permissions array type field, here all the needed permissions can be added for the extension functionality. As we will need the storage API in our app make sure to add “storage” to the permissions array.

The mainfest.json file will look as follows:

"permissions": ["activeTab", "storage"],"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"

5. Create UI elements:

According to our design will create 2 elements input and button.

Input element: As we can see below, the same component is handling the input for task ‘Title’ and its priority.

Input styling:

Button element:

Button styling:

Now that our elements are complete we can start working on our UI design and add some logic for adding and displaying the todos.

6. Updating our App.js

This is the most exciting part of creating our chrome extension. Let's add some logic for the app now!

The first step to make in this file is adding a state for our app. The initial code must consist of react template. Go ahead and remove all that template code as we will be using class-based react component as follows:

We have declared the chrome instance in the first line as you see. This is the basic syntax that is understood by chrome. This instance will be used further in our project to store and retrieve our tasks from the chrome storage API.

We have created a class-based react component and added a state where we can store title and priority for our next task to add to our tasks.

The tasks array will be used for representational purpose and displaying our tasks.

7. Store and retrieve tasks from the storage

Now we will add our function to get and store the tasks in chrome.storage API. Here we will use two methods namely set and get, these will help save and retrieve the tasks from the chrome.storage.

There are two ways to use the storage service in chrome API — local and sync.

  1. chrome.storage.local — storage.local will save the data on the local machine and won’t be synced across your logged-in devices.
  2. chrome.storage.sync — storage.sync will sync the data across devices all the Chrome browsers given the user has sync enabled.

Note: The chrome.storage is not a huge service that can save loads of data, also it is not encrypted hence you must not store valuable information there.

  1. Set tasks: here you can see the chrome.storage.sync.set function, the set function is used to set values and save them into storage.

2. Get tasks and set state: here we use the chrome.storage.sync.get function to get all the tasks from the storage. We use the callback function to access the tasks and then set our stage.

We will also use the componentDidMount lifecycle method, in there we will call the getTasks function, this will pull our tasks from the storage and set the state as soon as the extension is opened.

8. Delete task function

We need a function that will be bound to the delete task button as we can see in the UI design above. Here I have used the splice method of the array to remove the item from the tasks array and then save the array.

9. Add task function

The add task function will be used to add a task to the tasks array, it will take in 2 params from the state and create a new task. The task will be added to the existing tasks array in our current state and after added to the state we will update our storage to set the tasks.

The inputChangeHandler function will help us to handle change in the input fields in the UI.

10. Completing the UI

The UI will be completed by the following code and styled by App.css; feel free to make changes to your design!

App styling —

Thats it! The extension is ready to be tested.

Let's run the app:

  1. Open a terminal in the project directory and use the following command
npm start

This will create a folder named dev in the project directory.

2. Now open the Chrome Browser and open your extensions page by opening the following link: chrome://extensions/

3. Once opened click on the Load Unpacked button and select the dev folder in the project directory.

Make sure your extension is enabled, or enable it by clicking the pin icon in the extensions list.

Final product

This doesn’t stop here! Go ahead and create your version of the todo app or create something you’ve been trying to make.

Conclusion:

The Chrome extension is a great way to make apps that gives us a new way to connect to the user. The chrome extensions are getting newer users every day and the support for the same is increasing too. You can use the Chrome extensions documentation and get introduced to exciting API’s that will help you build complex and highly functional Chrome extensions.

Let me know how you liked today's blog in the comments!

--

--