In this tutorial, I will show how to write a chrome extension all the way. Writing chrome extensions is really not that hard and I think we all (developers) should know how to create them. Especially when 99% of the time we have a chrome browser open in front of us.
For those of you (like me) who can’t wait and want to get the code, Here it is on Github
What Do We Need?
- Chrome dev editor – this is not a must, but really helps to run the extension
- Chrome browser – no need to ask
- An idea for a new extension you’d like to have
How Chrome Extensions Work?
Basically, chrome extensions have two parts which you must be familiar with:
- Background code which runs behind the scenes and executes a piece of code usually on a predefined interval
- A code which runs when the extension is activated, usually runs once.
I’ll Explain:
A background process can be a code where you check the weather (or any other API) every fixed time and when something changes you notify the user about it. Not all extensions must have this section and in my example I didn’t use a background script.
The second script is in charge of the extension initialization. Usually, this will be a script which initializes the UI components and makes sure all the buttons, links, images etc are ready.
This example shows a basic chrome extension which opens a popup with a search input, searching this input leads to a new chrome tab with the relevant Google search results.
This is how the files tree looks like
We separate the styling, JavaScripts and images to different folders just to keep everything organized. It is recommended to include all sizes for the icons so it will look professional.
popup.html – this is the actual extension UI popup
background.html – this file loads the background script (which is empty in our case)
popup.js – initialization of the extension popup
Finally
After setting all the files, we need one more file to give google some information about our new extension.
manifest.json
Running Your Chrome Extension
After you have the extension ready, running it is pretty straight forward. If you’re using the chrome dev editor, just click the play button. After modifying the extension, in order to relaunch it, I had to right click and ‘remove from Chrome’ before starting it again. If you’re using your own editor, just go to chrome://extensions/ and drag and drop your extension folder there (make sure you’re in developer mode).
Get the full code from my Github