RSS

CEK.io

Chris EK, on life as a continually learning software engineer.

Scratching My Own Itch: A Chrome Extension Story

When we submit pull requests on BitBucket, my coworkers and I will generally draw attention when they are net-negative, removing more lines of code than they add. In some cases, it’s pretty obvious—entire files being deleted, etc. Oftentimes, however, it requires doing a bit of mental math to tally the difference between lines added and lines removed. For that reason, it’s gratifying to “scratch my own itch” by installing this extension to do it for me.

The “problem” already had a solution of sorts, in the form of a short jQuery script a coworker had pulled together:

(extension.js) download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var addVals, linesAdded, linesRemoved, offset;

addVals = function(className, symbolToReplace) {
  var results;
  results = [];
  $(className).each(function() {
    var val;
    val = $(this).html().replace(symbolToReplace, '');
    return results.push(parseInt(val));
  });
  return results.reduce(function(x, y) {
    return x + y;
  });
};

linesAdded = addVals('.lines-added', '+');
linesRemoved = addVals('.lines-removed', '-');
offset = linesAdded - linesRemoved;

A simple solution that, when run in the browser console, would log the offset. I just wanted to make it even simpler by removing that one extra step. That meant setting up a Chrome extension, which was a far easier process than I thought it might be.

A brief how-to

  • Set up a new directory with a manifest.json file, with a name, manifest_version of 2, a version,
  • To see it working, add an icon.png and list that file in manifest.json under browser_action.default_icon. By now, manifest.json should look something like this:
    {
        "name": "Hello World!",
        "manifest_version": 2,
        "version": "1.0",
        "description": "My first Chrome extension.",
        "browser_action": {
          "default_icon": "icon.png"
        }
      }
  • Go to chrome://extensions, tick ‘developer mode’, click ‘load unpacked extension’, and select your new folder–note your icon appear in the top right of your browser, next to your other extensions.
  • At this point, you have a Chrome extension! Of course, now you need to decide what you want it to do, but getting it started is that trivial. In my case, I didn’t even keep the default icon, since I just want a script to run on certain domains.
  • Publishing the extension requires a Chrome developer account (which requires a $5 payment), which you can set up here. From there, publishing the extension just requires compressing the folder to a zip file (right-click the folder, compress) and uploading.

Resources

Google’s documentation is pretty clear and helpful
Lifehacker has a decent intro tutorial.