How to Create Chrome Extension Using React in 4 Simple Steps

Rahul Mehra
2 min readOct 30, 2020

--

Photo by Nimit Kansagra from Pexels

Chrome Extension is a great tool to enrich and manipulate the browser experience of a user. Many companies also use it as an enhancement to their main application for increasing their user engagement. But the main issue which many developers face while creating a Chrome Extension is that almost all of the tutorials provided on the internet are using Vanilla JavaScript. This acts as a road blocker for developers accustomed to use libraries like React to speed up their development process.

So to help those, this article describes a four step process to create a Chrome Extension using React. So let’s get started!

Eject from Create React App Packaging

First and foremost we must eject from CRA. To do so execute the following command in your src directory.

npm run eject

If you are using yarn then you can use

yarn eject

Modifying manifest.json

CRA already provide us with a boilerplate manifest.json in the project_directory/public/ directory. Though the purpose of this manifest.json is to support PWA features(to know more try this link), we can still modify it as our Chrome Extension’s manifest.json. To get a basic skeleton for your manifest.json you can copy it from here. Now modify the Content Script array so that it contains our build output files.

modified manifest.json

Remove dynamic hash from webpack.config.js

The pre-configured Webpack of CRA gives in-built support for generating hashed output files. To make sure that these files have same name every time we build the project, we need to remove the [contenthash:8] tag from all the .js and .css files in project_directory/config/webpack.config.js. This will make it easy for mapping the output files in our manifest.json.

Changes for .js output files
Changes for .css output files

Append React app to DOM as a Content Script

Now in you index.js you need to provide an entry point to which we can append our react app. For this we will append it to the body tag in DOM of the target web page.

Changes in index.js for appending application in DOM

Here we have appended our div node with id “extension-div” to the body tag in DOM as a child element. This will attach our application to the web page on which the extension is running.

To utilize any Chrome Extension API, add /global chrome*/ at the top of your js file. Also you can add the background.js in your project_directory/public/ directory.

Changes to include background.js

That’s it! I hope you find this article useful. Feel free to comment below for any queries regarding the set up.

--

--

Rahul Mehra
Rahul Mehra

Written by Rahul Mehra

One must cultivate one’s own garden

No responses yet