How to build a chrome extension with React?

Estimated read time 3 min read

To build a Chrome extension with React, you can follow these general steps:

  1. Create a new React app using Create React App.
  2. Create a public folder in the root directory of the project and add a manifest.json file with the required fields for a Chrome extension.
  3. Create a background.js file in the public folder with the required background script for a Chrome extension.
  4. Build the React app using the npm run build command.
  5. Load the built React app and the manifest.json file in the Chrome browser as an unpacked extension.

Here’s a more detailed explanation of each step:

  1. Create a new React app using Create React App:
npx create-react-app my-extension
cd my-extension
  1. Create a public folder in the root directory of the project and add a manifest.json file with the required fields for a Chrome extension:
{
  "manifest_version": 2,
  "name": "My Extension",
  "version": "1.0.0",
  "description": "My Chrome Extension",
  "icons": {
    "16": "favicon.ico",
    "48": "logo.png",
    "128": "logo.png"
  },
  "browser_action": {
    "default_popup": "index.html"
  },
  "permissions": ["activeTab"]
}

In this code, we’re defining a manifest.json file with the required fields for a Chrome extension. We’re defining the name, version, description, icons, browser action, and permissions fields.

The browser_action field defines a default popup HTML file called index.html. We’ll create this file later.

  1. Create a background.js file in the public folder with the required background script for a Chrome extension:
chrome.browserAction.onClicked.addListener((tab) => {
  chrome.tabs.executeScript({
    file: 'index.js'
  });
});

In this code, we’re defining a background.js file with a background script that listens for the browser action button to be clicked. We’re using the chrome.tabs.executeScript method to execute the index.js file in the current tab.

  1. Build the React app using the npm run build command:
npm run build

This command will create a build folder with the built React app files.

  1. Load the built React app and the manifest.json file in the Chrome browser as an unpacked extension:
  • Open the Chrome browser and navigate to the Extensions page (chrome://extensions/).
  • Turn on the Developer mode switch.
  • Click on the Load unpacked button and select the build folder that was created in step 4.
  • The extension should now be loaded and the browser action button should be visible in the toolbar.

By following these steps, you can build a Chrome extension with React and add it to the Chrome browser. You can customize the extension by adding more React components and modifying the manifest.json and background.js files.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply