Fix another race condition triggered when two vanadium runtimes
authenticate at the same time (like on the tutorials).

The logic for checking whether the NaCl plugin is active is a little
more complicated, since we have to make sure it emitted a 'ready' event.

If the nacl plugin exists but is not ready, we need to queue the
callback to be called later.

Change-Id: I0958a9a3232fc18edd8f313902fb5bef0f1cd4a8
diff --git a/extension/src/background/index.js b/extension/src/background/index.js
index 77c6abb..e13c5ef 100644
--- a/extension/src/background/index.js
+++ b/extension/src/background/index.js
@@ -238,19 +238,23 @@
 
 // Return true if the nacl plug-in is running.
 BackgroundPage.prototype.naclPluginIsActive = function() {
-  return this.hasOwnProperty('nacl');
+  return this.hasOwnProperty('nacl') && this.nacl.isReady;
 };
 
 // Start the nacl plug-in -- add it to the page and register handlers.
 BackgroundPage.prototype.startNaclPlugin = function(cb) {
   var bp = this;
   cb = cb || function() {};
-  bp.nacl = new Nacl();
-  bp.registerNaclListeners();
-  bp.nacl.once('ready', function() {
-    bp.authHandler = new AuthHandler(bp.nacl.channel);
-    cb();
-  });
+
+  if (!bp.nacl) {
+    bp.nacl = new Nacl();
+    bp.registerNaclListeners();
+    bp.nacl.once('ready', function() {
+      bp.authHandler = new AuthHandler(bp.nacl.channel);
+    });
+  }
+
+  bp.nacl.once('ready', cb.bind(bp));
 };
 
 // Stop the nacl plug-in - remove it from the page and clean up state.
diff --git a/extension/src/background/nacl.js b/extension/src/background/nacl.js
index 27bed46..e55aa97 100644
--- a/extension/src/background/nacl.js
+++ b/extension/src/background/nacl.js
@@ -108,6 +108,7 @@
         nacl._initialized = true;
         nacl._sendQueuedMessages();
         nacl.channel.ready();
+        nacl.isReady = true;
         nacl.emit('ready');
       });
     });