Fix bg.js functions being run repeteadly

Some functions in bg.js only need to be called once when the extension
starts up. Unfortunately, since event pages and service workers unload
bg.js to save resources, when bg.js is spinned up again, those functions
are called again.

This CL fixes this by checking whether it's the first time it's being
run or not.

Change-Id: I9b7867b3db825c0d1183acd13a0a22a58a999a74
diff --git a/src/bg.js b/src/bg.js
index 9d22c29..a0864d8 100644
--- a/src/bg.js
+++ b/src/bg.js
@@ -15,14 +15,39 @@
 self.XMLHttpRequest = XMLHttpRequest;
 // #!endif
 
+// Returns whether the script is being ran when the extension starts up. It does
+// so on a best-effort-basis.
+function isExtensionStartup() {
+  // If chrome.storage.session isn't implemented in this version of Chrome, we
+  // don't know whether it's the extension startup.
+  if (!chrome.storage.session) return Promise.resolve(true);
+
+  return new Promise((resolve, reject) => {
+    return chrome.storage.session.get('hasAlreadyStarted', v => {
+      resolve(v.hasAlreadyStarted !== true);
+    });
+  });
+}
+
+// Sets that the extension has already started up
+function setHasAlreadyStarted() {
+  if (!chrome.storage.session) return;
+  chrome.storage.session.set({
+    hasAlreadyStarted: true,
+  });
+}
+
 actionApi.onClicked.addListener(() => {
   chrome.runtime.openOptionsPage();
 });
 
 const killSwitchMechanism = new KillSwitchMechanism();
 
-chrome.alarms.create('updateKillSwitchStatus', {
-  periodInMinutes: PRODUCTION ? 30 : 1,
+chrome.alarms.get('updateKillSwitchStatus', alarm => {
+  if (!alarm)
+    chrome.alarms.create('updateKillSwitchStatus', {
+      periodInMinutes: PRODUCTION ? 30 : 1,
+    });
 });
 
 chrome.alarms.onAlarm.addListener(alarm => {
@@ -50,9 +75,6 @@
 // Clean up optional permissions and check that none are missing for enabled
 // features, and also handle background option changes as soon as the extension
 // starts and when the options change.
-cleanUpOptPermissions();
-handleBgOptionsOnStart();
-
 chrome.storage.sync.onChanged.addListener(changes => {
   cleanUpOptPermissions();
 
@@ -83,3 +105,12 @@
       console.warn('Unknown message "' + msg.message + '".');
   }
 });
+
+// This should only run once when the extension starts up.
+isExtensionStartup().then(isStartup => {
+  if (isStartup) {
+    cleanUpOptPermissions();
+    handleBgOptionsOnStart();
+    setHasAlreadyStarted();
+  }
+});