Chrome extensions come in really handy when it comes to blocking ads, improving productivity, managing cluttered tabs, and of course improving the readability of code on GitHub for developers.❤️
In this blog, let’s create a Chrome extension in an easy 4-step process using React, Typescript, and Vite bundler.
Let us assume that nodejs is pre-installed, if not then you can follow this setup nodejs and dependencies on the development/local machine.
Now, since we are all set, Let’s begin!!
Step 1: Initialise a new Vite Project
Create a new project using Vite.
npm create vite@latest
This command will prompt for a few inputs from the user:
- Project Name: Project name that you want to give to your project.
- Select a Framework: Choose ‘React’ as that is what we are going with in this tutorial.
- Select a variant: Choose ‘Typescript’ there to keep up with this tutorial.
Step 2: Install Dependencies & Run Application on local
Now change the directory to the created/initialized folder and install the dependencies.
> cd vite-ts-react-test
> npm install
Now to test if everything worked fine. Run the following command in the terminal.
npm run dev
This will prompt a new message on the command line similar to below screenshot:
This signifies that everything is running fine up to this point. Once you open the above shown – http://localhost:5173/ on the browser, you will a see Vite welcome page, something like this:
Next exit from the vite localhost prompt using ‘CTRL+C’ and run the command to build the project
npm run build
An output something like the above will come up on the terminal/cmd.
Step 3: Create a Chrome Extension and Validate it
At the end of step 2, the boilerplate will be ready inside the project directory. You will see a lot of stuff inside the directory but don’t worry we are only interested in a few of these:
- Dist: Build command creates this folder dynamically by copying a few files from other folders or as instructed in the config file. For this tutorial default configuration will work. So, we are not going to touch anything inside it.
- Public: We will add all of our project files and static files in this folder and build command will add those to the dist folder, once the build is successful.
- Src: This is where magic happens. This is where we write typescript code, you will also some typescript written in this blog.
Now go to public folder and create a new file manifest.json:
{
"manifest_version": 3,
"name": "vite-ts-react-test",
"version": "1.0",
"description": "",
"action": {
"default_popup": "index.html"
},
"permissions": [
"scripting",
"tabs",
"activeTab"
],
"host_permissions": [
"https://*/*",
"http://*/*"
],
"icons": {
"16": "images/16x16.png",
"32": "images/32x32.png"
}
}
Run the below command to build the project:
npm run build
Now go to chrome://extension, and enable developer mode if not already set. Click on “Load Unpacked” to pick dist folder from the local file system.
Voila!! Our Chrome Extension is ready to try.
If you are still following up to this point, then a new extension will be available on your extension list. You can go ahead and click on the extension on the Chrome menu bar, you will see the Vite welcome page as mentioned above in this page.
Step 4: Scripting in Chrome Extension using React and Typescript
In this step, let’s try to do some scripting to see if it works. Let’s go to the “src” folder to write some typescript code.
In this script, we will write a code using Chrome API to change the background color of the web page.
let’s install the Chrome API using the below command:
npm install -D @types/chrome
Now look for src/App.tsx file in the project directory and change the code as below:
// import { useState } from 'react'
import reactLogo from './assets/react.svg'
import viteLogo from '/vite.svg'
import './App.css'
function App() {
// const [count, setCount] = useState(0)
const onClick = async () => {
let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
chrome.scripting.executeScript({
target: { tabId: tab.id! },
func: () => {
document.body.style.backgroundColor = 'green';
}
});
}
return (
<>
<div>
<a href="https://vitejs.dev" target="_blank">
<img src={viteLogo} className="logo" alt="Vite logo" />
</a>
<a href="https://react.dev" target="_blank">
<img src={reactLogo} className="logo react" alt="React logo" />
</a>
</div>
<h1>Vite + React</h1>
<div className="card">
<button onClick={() => changeColorOnClick()}>
Change Color
</button>
<p>
Edit <code>src/App.tsx</code> and save to test HMR
</p>
</div>
<p className="read-the-docs">
Click on the Vite and React logos to learn more
</p>
</>
)
}
export default App
if you look closely most of the code is already available. The only new addition is a function “changeColorOnClick“.
const changeColorOnClick = async () => {
let [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
chrome.scripting.executeScript({
target: { tabId: tab.id! },
func: () => {
document.body.style.backgroundColor = 'green';
}
});
}
Now don’t forget to build it again and refresh the extension from chrome://extensions.
npm run build
and it’s done!!
Give it a try by visiting any website with considerably white background like singlequote.blog.
Tips and Tricks: Running the build command after every change could be tiresome and error-prone. If you forgot to refresh and are wondering why the changes are not coming up – Rollup is here to rescue us. Read about Chrome Extension using Node + Rollup plugin: Stepwise Process.