How to use the Gmail API in a Chrome extension
Chrome extensions are awesome. The Gmail API is awesome. It should be easy to use the two together. And it actually is easy to use the two together, however there’s a lot of noise out there to get things to work properly, so I wanted to write this blog post to give a very clear front to back example. Here is a gist link that is a barebones extension to get you started.
Step 1: Register for the Gmail API
Follow this link to start enable dev access to the Gmail API:
Step 2: Create a Chrome extension
Creating a chrome extension is super easy. All you need is a folder with a manifest.json file (included in the above gist).
Go to chrome://extensions, check “Developer Mode,” and then click on “Load Unpacked Extension.” Navigate to the folder where the manifest.json file is located and choose that.
You should then have something that looks like this:
Note the “ID” field. When you load an unpacked extension a unique ID is generated automatically. If you want to make sure that your extension always has the same ID you’ll need to upload the extension to the chrome web store and install the extension from there. This adds some annoyance to development because the ID is needed for Oauth2.
Step 3: Create Client Access ID
In the Google Cloud Console go to APIs & Auth -> Credentials. Then click on “Create new Client ID.”
In the Create Client ID dialog choose “Installed Application” and then “Chrome Application.” In the Application ID textbox put in the ID of the extension.
You will now have a new Client ID show up on the list, you’ll need to copy this client id and put it in the Oauth2 section of your manifest.json.
In the linked gist there is an included background.js file that already does the necessary work to authorize and load the Gmail client library. You simply need to replace the clientID with the one from above.
Step 5: Profit!
Chrome extensions are super powerful, and there’s a lot of really cool functionality that Chrome exposes. Whether you’re using it for an internal tool, or selling a service hopefully this post will make it a bit easier to make something that people want.
- Chrome extension capabilities have been improving massively over the past couple of years as Chrome OS matures and Google pushes real applications. There is unfortunately a lot of obsolete code and articles out there using outdated APIs. This is becoming a real hindrance to finding the right way to do things.
- No real mind has been put towards security in the included gist — so if you’re going to make something real with this be sure to give it a proper security pass.
- I included an external Base64 library instead of using the browser’s built in atob/btoa functionality because the threads from Gmail’s response use a slightly different Base64 encoding that is incompatible with the browser’s. So annoying.