title: How to pass a blob from a Chrome extension to a Chrome app
body: <p><strong>A Little Background</strong></p>
  
  <p>I've been working for a couple of days on a Chrome extension that takes a screenshot of given web pages multiple times a day. I used <a href="https://github.com/mrcoles/full-page-screen-capture-chrome-extension" rel="nofollow noreferrer">this</a> as a guide and things work as expected. </p>
  
  <p>There's one minor requirement extensions can't meet, though. The user must have access to the folder where the images (screenshots) are saved but <a href="https://stackoverflow.com/questions/19802032/how-can-a-chrome-extension-save-many-files-to-a-user-specified-directory">Chrome Extensions don't have access to the file system</a>. Chrome Apps, on the other hand, do. Thus, after much looking around, I've concluded that I must create both a Chrome Extension and a Chrome App. The idea is that the extension would create a blob of the screenshot and then send that blob to the app which would then save it as an image to a user-specified location. And that's exactly what I'm doing — I'm creating a blob of the screentshot on the extension side and then sending it over to the app where the user is asked to choose where to save the image.</p>
  
  <p><strong>The Problem</strong></p>
  
  <p>Up to the saving part, everything works as expected. The blob is created on the extension, sent over to the app, received by the app, the user is asked where to save, and the image is saved.... THAT is where things fall apart. <strong>The resulting image is unusable.</strong> When I try to open it, I get a message that says <em>"Can't determine type".</em> Below is the code I'm using: </p>
  
  <ol>
  <li><p>First ON THE EXTENSION side, I create a blob and send it over, like this:</p>
  
  <pre><code> chrome.runtime.sendMessage(
      APP_ID, /* I got this from the app */
      {myMessage: blob}, /* Blob created previously; it's correct */
      function(response) {
        appendLog("response: "+JSON.stringify(response));
      }
   );
  </code></pre></li>
  <li><p>Then, ON THE APP side, I receive the blob and attempt to save it like this:</p>
  
  <pre><code>// listen for external messages
  chrome.runtime.onMessageExternal.addListener(
    function(request, sender, sendResponse) {
      if (sender.id in blacklistedIds) {
        sendResponse({"result":"sorry, could not process your message"});
        return;  // don't allow this extension access
      } else if (request.incomingBlob) {
        appendLog("from "+sender.id+": " + request.incomingBlob);
  
        // attempt to save blob to choosen location
        if (_folderEntry == null) {
           // get a directory to save in if not yet chosen
           openDirectory();
        }
        saveBlobToFile(request.incomingBlob, "screenshot.png");
  
        /*
        // inspect object to try to see what's wrong
        var keys = Object.keys(request.incomingBlob);
        var keyString = "";
        for (var key in keys) {
           keyString += " " + key;
        }
        appendLog("Blob object keys:" + keyString);
        */
  
        sendResponse({"result":"Ok, got your message"});
      } else {
        sendResponse({"result":"Ops, I don't understand this message"});
      }
    }
  );
  </code></pre>
  
  <p>Here's the function ON THE APP that performs the actual save:</p>
  
  <pre><code>function saveBlobToFile(blob, fileName) {
    appendLog('entering saveBlobToFile function...');
    chrome.fileSystem.getWritableEntry(_folderEntry, function(entry) {         
      entry.getFile(fileName, {create: true}, function(entry) {         
        entry.createWriter(function(writer) {
          //writer.onwrite = function() {
          //   writer.onwrite = null;
          //   writer.truncate(writer.position);
          //};
          appendLog('calling writer.write...');
          writer.write(blob);                       
          // Also tried writer.write(new Blob([blob], {type: 'image/png'}));
        });
      });
    });
  }
  </code></pre></li>
  </ol>
  
  <p>There are no errors. No hiccups. The code works but the image is useless. What exactly am I missing? Where am I going wrong? Is it that we can only pass strings between extensions/apps? Is the blob getting corrupted on the way? Does my app not have access to the blob because it was created on the extension? Can anyone please shed some light?</p>
  
  <p><strong>UPDATE (9/23/14)</strong>
  Sorry for the late update, but I was assigned to a different project and could not get back to this until 2 days ago.</p>
  
  <p>So after much looking around, I've decided to go with @Danniel Herr's suggestion which suggests to use a SharedWorker and a page embedded in a frame in the app. The idea is that the Extension would supply the blob to the SharedWorker, which forwards the blob to a page in the extension that is embedded in a frame in the app. That page, then forwards the blob to the app using parent.postMessage(...). It's a bit cumbersome but it seems it's the only option I have. </p>
  
  <p>Let me post some code so that it makes a bit more sense:</p>
  
  <p><strong>Extension:</strong> </p>
  
  <pre><code>var worker = new SharedWorker(chrome.runtime.getURL('shared-worker.js'));
  worker.port.start();
  worker.postMessage('hello from extension'); // Can send blob here too
  worker.port.addEventListener("message", function(event) {
     $('h1Title').innerHTML = event.data;
  });
  </code></pre>
  
  <p><strong>proxy.js</strong></p>
  
  <pre><code>var worker = new SharedWorker(chrome.runtime.getURL('shared-worker.js'));
  worker.port.start();
  
  worker.port.addEventListener("message",
     function(event) {      
        parent.postMessage(event.data, 'chrome-extension://[extension id]');
     }
  );
  </code></pre>
  
  <p><strong>proxy.html</strong></p>
  
  <pre><code>&lt;script src='proxy.js'&gt;&lt;/script&gt;
  </code></pre>
  
  <p><strong>shared-worker.js</strong></p>
  
  <pre><code>var ports = [];
  var count = 0;
  onconnect = function(event) {
      count++;
      var port = event.ports[0];
      ports.push(port);
      port.start(); 
  
      /* 
      On both the extension and the app, I get count = 1 and ports.length = 1
      I'm running them side by side. This is so maddening!!!
      What am I missing?
      */
      var msg = 'Hi, you are connection #' + count + ". ";
      msg += " There are " + ports.length + " ports open so far."
      port.postMessage(msg);
  
      port.addEventListener("message",       
        function(event) {
          for (var i = 0; i &lt; ports.length; ++i) {
              //if (ports[i] != port) {
                  ports[i].postMessage(event.data);
              //}
          }
      });
  };
  </code></pre>
  
  <p><strong>On the app</strong></p>
  
  <pre><code>context.addEventListener("message", 
      function(event) {
          appendLog("message from proxy: " + event.data);
      } 
  );
  </code></pre>
  
  <p>So this is the execution flow... On the extension I create a shared worker and send a message to it. The shared worker should be capable of receiving a blob but for testing purposes I'm only sending a simple string. </p>
  
  <p>Next, the shared worker receives the message and forwards it to everyone who has connected. The proxy.html/js which is inside a frame in the app has indeed connected at this point and should receive anything forwarded by the shared worker. </p>
  
  <p>Next, proxy.js [should] receives the message from the shared worker and sends it to the app using parent.postMessage(...). The app is listening via a window.addEventListener("message",...). </p>
  
  <p>To test this flow, I first open the app, then I click the extension button. I get no message on the app. I get no errors either. </p>
  
  <p>The extension can communicate back and forth with the shared worker just fine. The app can communicate with the shared worker just fine. However, the message I sent from the extension->proxy->app does not reach the app. What am I missing?</p>
  
  <p>Sorry for the long post guys, but I'm hoping someone will shed some light as this is driving me insane.</p>
  
  <p>Thanks</p>