How to Build A Chrome Extension: Part 3
Building A Chrome Extension
Welcome to Part 2 of my “How to Build A Chrome Extension” multipart tutorial if you need an overview of Project Concepts, Structure, and Terminology check out my How to Build A Chrome Extension Part 1: A Birds Eye Overview or How to Build A Chrome Extension Part 2: Understanding the Chrome API.
Here we are going make a chrome extension that displays a window with a list of the Reddit Subreddit that the user’s current url tab has been posted on.
So for chrome to enable us to have access to the users tab
instances, and we want to make reddit api calls we need to add the following permission to our manifest.json
{
"permissions":["tabs","https://www.reddit.com/*","http://www.reddit.com/"]
}
Here we want a subwindow to display when when a user clicks our extension we are going to need to declare a browser_action
inside our manifest.json
and lets tell it to load our popup.html
file when the user clicks the icon. We can do that by adding the following browser_action
object inside our manifest.json
file.
"browser_action": {
"default_title": "RedditLabs",
"default_popup": "popup.html",
"default_icon":"img/default-icon.png"
},
So you’re prolly asking, “where does the logic to make Reddit API calls go?” because I did.
We’ll you can load in .js
files into the popup.html
file defined in our manifests.json
file and that will work just fine, however you should use the background.js script for this that you can declare in your manifest.json
browser_action
object by adding
`background_page`:`background.html`
Let me clear up some things that may be confusing when looking at this. The background page is in .html
but is not attached to your apps DOM Events
.
Here the popup.html
file will simply be a dumb view, only able to accept parameters from the background.html
that we’ll set up to do the heaving lifting, ergo making the our Reddit API Calls.
To enable the popup.html
to awuire parameters from our background worker page we need to add the following refrence to our popup.html
const worker = chrome.extension.getBackgroundPage()
You now have access to the full scope of functions of any script tag loaded into the background.html
. For instance if the background.html
page includes:
<html>
<script>
function foo(param){
console.log("foo: ", param)
}
</script>
</html>
then in our popup.html
page we can access it by:
const worker = chrome.extension.getBackgroundPage()
worker.foo("bar")
So knowing that lets enable us into being able to access the console
object in our worker page inside our popup.html
page, to do this we add the following to our background.html
<html>
<script>
function chromeConsole(type="log",msg){
return {type:"log",msg}
}
</script>
</html>
Then use chromeConsole()
unstead of console.log()
and add
worker.chromeConsole(type="log",msg){
console[type](msg)
}
to get them to emit to our popup.html page.