Report UI Latency timings to Google Analytics

Listen to `timing-report` CustomEvents sent from PolyGerrit on document
and report latency times to Google Analytics.

Also see https://gerrit-review.googlesource.com/83530

Change-Id: Id63778dcc562e2d85c33f9e9d11afc54a888afe1
diff --git a/background.js b/background.js
index 72b681d..d936951 100644
--- a/background.js
+++ b/background.js
@@ -18,7 +18,8 @@
 
 (function() {
   var ga = document.createElement('script');
-  ga.type = 'text/javascript'; ga.async = true;
+  ga.type = 'text/javascript';
+  ga.async = true;
   ga.src = 'https://ssl.google-analytics.com/ga.js';
   var s = document.getElementsByTagName('script')[0];
   s.parentNode.insertBefore(ga, s);
@@ -26,10 +27,13 @@
 
 var RequestType = {
   NAV: 'nav',
+  TIMING: 'timing-report',
 };
 
-chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
-  if (request.type === RequestType.NAV) {
+chrome.runtime.onMessage.addListener(function(request, detail, sendResponse) {
+  if (request.type === RequestType.TIMING) {
+    _gaq.push(['_trackTiming', detail.category, detail.name, detail.name]);
+  } else if (request.type === RequestType.NAV) {
     _gaq.push(['_trackPageview', request.url]);
   }
 });
@@ -141,7 +145,7 @@
 chrome.storage.onChanged.addListener(function(changes, namespace) {
   if (namespace !== 'sync') { return; }
 
-  for (key in changes) {
+  for (var key in changes) {
     if (key === 'canary') {
       useCanary = changes[key].newValue;
     }
diff --git a/content.js b/content.js
index 0ad4756..d96f0ae 100644
--- a/content.js
+++ b/content.js
@@ -20,5 +20,8 @@
   if (isPolyGerrit) {
     // TODO(andybons): Track actions and integrate with the Gerrit JS API.
     // PageJS isn't in scope and is a pain to latch on to for navigation events.
+    document.addEventListener('timing-report', function(e) {
+      chrome.runtime.sendMessage({type: 'timing-report', detail: e.detail});
+    });
   }
 })();
diff --git a/manifest.json b/manifest.json
index d2565a8..9fca4ae 100644
--- a/manifest.json
+++ b/manifest.json
@@ -2,7 +2,7 @@
   "manifest_version": 2,
   "name": "Gerrit UI Switcher",
   "description": "Easily switch between the current Gerrit UI and the new PolyGerrit UI",
-  "version": "0.5.0",
+  "version": "0.5.1",
   "background": {
     "scripts": [
       "background.js"