Chrome Extensions using Vite + Typescript + React: Stepwise Process

arglee

Ashish Mishra

Posted on November 3, 2023

Chrome Extensions using Vite + Typescript + React: Stepwise Process

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.❤️


Image Courtesy: singlequote.blog

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 Project

Create a new project using Vite.

npm create vite@latest
Enter fullscreen mode Exit fullscreen mode

This command will prompt for a few inputs from the user:

  1. Project Name: Project name that you want to give to your project.
  2. Select a Framework: Choose ‘React’ as that is what we are going with in this tutorial.
  3. Select a variant : Choose ‘Typescript’ there to keep up with this tutorial.


Image Courtesy: singlequote.blog

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
Enter fullscreen mode Exit fullscreen mode

Now to test if everything worked fine. Run the following command in the terminal.

npm run dev
Enter fullscreen mode Exit fullscreen mode

This will prompt a new message on the command line similar to below screenshot:


Image Courtesy: singlequote.blog

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:


Image Courtesy: singlequote.blog

Next exit from the vite localhost prompt using ‘CTRL+C’ and run the command to build the project

npm run build
Enter fullscreen mode Exit fullscreen mode


Image Courtesy: singlequote.blog

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:

  1. Dist: The “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.
  2. Public: We will add all of our project files and static files in this folder and the “build” command will add those to the dist folder, once the build is successful.
  3. Src: This is where magic happens. This is where we write typescript code, you will also some typescript written in this blog.


Image Courtesy: singlequote.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"
    }
  }
Enter fullscreen mode Exit fullscreen mode

Run the below command to build the project:

npm run build
Enter fullscreen mode Exit fullscreen mode

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 on this page.

Step 4: Scripting in Chrome Extension

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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';
      }
    });
  }
Enter fullscreen mode Exit fullscreen mode

Now don’t forget to build it again and refresh the extension from chrome://extensions.

npm run build
Enter fullscreen mode Exit fullscreen mode

and it’s done!!

Give it a try by visiting any website with a 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.

💖 💪 🙅 🚩
arglee
Ashish Mishra

Posted on November 3, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related