DEV Community

J-Sandaruwan
J-Sandaruwan

Posted on • Updated on

Chrome extension with React

main image

What is a Google Chrome Extension?

Chrome extensions modify the browser's capabilities. This involves introducing new Chrome features or changing the program's behavior to be more user-friendly.

1.Create React App

First we need to crate a react application using typescript,

npx create-react-app chrome-test-extension --template typescript
Enter fullscreen mode Exit fullscreen mode

2.React app convert to google extension

In this step we need to config manifest.json, This file located in to public folder. Basically we can update the our extension name, description, version, manifest_version, action and icons.

In this code we use manifest version 3 for our project.

{
   "name": "Chrome React Test Extension",
   "description": "Test Chrome extensions",
   "version": "0.1",
   "manifest_version": 3,
   "action": {
       "default_popup": "index.html",
       "default_title": "Open the popup"
   },
   "icons": {
       "16": "logo192.png",
       "48": "logo192.png",
       "128": "logo192.png"
   }
}
Enter fullscreen mode Exit fullscreen mode

3.Pop-up architecture

In this project action on index.html.Default body size we can increase pop-up size in index.css. But we can use that use maximum width: 800px and maximum height: 600px.

body {
 width: 600px;
 height: 400px;
 ...
}
Enter fullscreen mode Exit fullscreen mode

4.Build our application

Before build that project we need to change some of part that project.The normal build file structure looks nice, however with Chrome, we'd get CSP (Content Security Policy) problems. To avoid adding extra JavaScript files, CRA inserts inline JavaScript code right on the HTML page while building the application. This works on a website, but not an extension.

Therfore we will update package.json scripts section build part to

"build": "INLINE_RUNTIME_CHUNK=false react-scripts build",
Enter fullscreen mode Exit fullscreen mode

If we build index.html for our project, it will not include any references to inline JavaScript code.

without INLINE_RUNTIME_CHUNK=false

without INLINE_RUNTIME

with INLINE_RUNTIME_CHUNK=false

with INLINE_RUNTIME

Now we can build our project.

yarn build
Enter fullscreen mode Exit fullscreen mode

5.Add the extension to the browser

Easily go to the mange extension in chrome use that link chrome://extensions

Before add the build file we want to active developer mode in chrome extensions.

developer mode

Select your build folder under Load unpacked. Your extension has been loaded and is now listed. Like so:

chrome://extensions

Image code

Image code 2

That way to Chrome extension with react.Let's meet again for the new tutorial (how to get the URL of the current tab from Chrome extension.

Thank you,
J-Sandaruwan.
linkedin

Top comments (0)