This month, I started to build my new product. It helps convert any website to JSON, XML, CSV, or any other format. I wrote my own Chrome extension for pointing to the fields in websites.
Note: If you don’t want to read this article and just want to start coding, you can find the Git repo at the end.
We need to render our app on the visited website when a user clicks the render element button in the popup.
So, let’s get started.
│ └── main.js [We will use that build file as content script]
├── js [Where our development file is stored]
│ ├── components [We are storing components in this folder]
│ │ └── Header.js
│ ├── main.js [Our main file, that renders our app]
└── popup.html [Our html file for rendering popup after clicking the icon in the bar]
manifest.json, as we need that file for providing information about our Chrome extension.
Every extension has a JSON-formatted manifest file, named
manifest.json, that provides important information like name, version, and permissions.
And here is how it looks:
After creating the manifest file, we need to configure our project environment and structure.
Let’s start creating out project structure — so open your terminal and follow my steps!
As you can see, there are two scripts
watchcommand watches your
main.jsand compiles if there was a change or if dependencies are imported from
buildcommand builds your files into the
- Create a components folder in
touch src/js/main.js src/js/popup.js src/popup.html
The popup appears at the top of the bar in Chrome when a user clicks the icon of the extension.
The React App will be rendered in the content when a
startApp message comes from the popup. The popup will share a
startApp message with the app.
popup.html file with the following HTML:
There is a button in the popup which sends a message to our
main.js file when a user is clicked.
And edit your
popup.js file with the following:
chrome.tabs.sendMessage method shares the message with a listener. Our listener is working in the
At this point,
main.js should listen to messages which are coming from
We can listen to messages with the
chrome.runtime.onMessage.addListener method. And here is how our
main.js file looks:
- Imported React and ReactDOM libraries.
- Created an App class for rendering a React element.
- Added an event listener function for listening for messages which are coming from
- Created an
injectAppfunction that created a div, and injected it into a body. We rendered our
<App />component inside it.
For testing your extension:
- If you didn’t build your files, build them by running the
npm run buildcommand
- Go to “chrome://extensions”
- Check the “Developer Mode” switcher
- Click the “Load Unpacked” button, then select your project folder.