› ~/

Writing a Chrome Extension With React

2017-06-19

Writing a chrome extension is essentially just bundling HTML, CSS and JS into a zip file. It’s not super complicated, so how hard can it be to write one with React.js?

My plan was to write an extension that I could run locally in an environment that would reload when I made changes, so my choice on technology was as follows.

Turns out that the answer to that question is fairly easy! The process of setting React with create-react-app is straight forward and installing Material UI posed no issues either. The result of this work is Mynt, an app to shows the current prices of crypto currencies such as Bitcoin, Litecoin and Ethereum.

Storage issue

One big problem I faced was how I would emulate the chrome.storage API that is available to chrome extensions, because they are not reachable to pages than the specific chrome pages such as New Tab, History and similar.

My solution was to wrap chrome.storage into a class that would check if that API is available, if it wasn’t available I would use the window.localStorage API instead.

Manifest.json

Every chrome extension requires a manifest.json file to be included in your bundle. The easiest way to making this happen is to place your manifest file inside the public folder, since everything in it will be put inside the builder folder by create-react-app

Bundle the extension

Turned out that storage was my biggest obstacle, so everything after that was smooth sailing!

I would like to share some tips before I end this post, namely that it’s a good reason to extend the default build script in create-react-app with a step that also zips the build folder.

"scripts": {
  "build": "react-scripts build",
  "build-pack":"npm run build && npm run zip",
  "zip": "bestzip bundle.zip build/*"
}

Happy coding!

Written by
Andreas