Learn how to create a custom chrome extension and use it to inject a custom React component into any site.
This article was original posted on myweekinjsThis week I set out to create a chrome extension and utilise JavaScript and React to inject a component into a website. The result is a beautiful combination of Mutation Observers and JavaScript goodness!
The code can be found on Github
options.js
, options.html
, and popup.js
files. In the manifest.json
file I removed the options_page
key as well as the storage
value from the permissions
array. Next, you want to add https://www.myweekinjs.com/
to the permissions
array.
I will be referencing myweekinjs a few times, this could be any website that you wish to inject a React component into.
Next, I created an app.js
with a simple console.log
to test that the script works, and updated the background.js
to;
background.js
script will do the following;
app.js
filewebpack.config.js
file to compile our React and Javascript. At this point, I’d recommend creating a dist folder with the current files (minus the app.js
), and unpacking that folder as our extension. This way you can compile into this dist folder and won’t include your node_modules into the extension.
We’ll use this awesome resource to generate our webpack and .babelrc files createapp.dev
npm init -y
and install the packages outlined by the resourcewebpack.config.js
and .babelrc
files into your projectscripts
from the package.json
webpack.config.js
change the entry and output settings;
build-dev
script to;
.babelrc
, they should be easy to fix though, mainly issues about using double quotes.
Running the build-prod
script will compile the app.js
file. After a unpack and reload, you should be greeted with the same console.log
as before. A long process to get where we were, but now things get interesting!
load
and contains our main callback function which I called app.
target-test
div on our test page. The following code is added to the load callback.