title: DOM Exception 12 for window.postMessage
body: <p>I'm learning to build Chrome Extensions, and I'm trying to follow one of the instructions in the official Guide <a href="https://developer.chrome.com/extensions/content_scripts.html#host-page-communication" rel="nofollow">here</a>.</p>
  
  <p>What I am trying to accomplish is:</p>
  
  <ol>
  <li>background.js shows page action for targetted URLs.</li>
  <li>Page action executes a script when clicked.</li>
  <li>Executed script injects javascript on page.</li>
  </ol>
  
  <p>So far, so good! I use the following script to inject into the page.</p>
  
  <pre><code>var injectJS = function(url, cb) {
      var h = document.getElementsByTagName('head')[0],
          s = document.createElement('script');
      s.type = 'text/javascript';
      s.src = url;
      if (cb)
          s.onload = cb;
      h.appendChild(s);
  };
  injectJS(chrome.extension.getURL('script/do_something.js'));
  </code></pre>
  
  <p>Now, I want the injected script to be able to communicate back to the extension.<br>
  It seems like what I am looking for is what's described in the documentation.</p>
  
  <p><a href="https://developer.chrome.com/extensions/content_scripts.html#host-page-communication" rel="nofollow">https://developer.chrome.com/extensions/content_scripts.html#host-page-communication</a></p>
  
  <p>The problem is, when I try to do <code>window.postMessage</code> the console shows an error "DOM Exception 12".</p>
  
  <hr>
  
  <p>Edit: The first problem running the sample code was solved.<br>
  The other error I get, from the smae code is from <code>port.postMessage</code>:</p>
  
  <p><code>Uncaught Error: Attempting to use a disconnected port object</code></p>
  
  <p>Here's the code:</p>
  
  <pre><code>var port = chrome.runtime.connect();
  
  // Respond to messages from the injected script to collect results
  window.addEventListener('message', function(e) {
      if (e.source != window)
          return;
      if (e.data.type &amp;&amp; (e.data.type == 'FROM_PAGE')) {
          console.log('Content script received: %s', e.data.text);
          port.postMessage(e.data.text);
      }
  }, false);
  </code></pre>
  
  <p>Basically I'm trying to persist some data temporarily while a page reloads. The content script/injected script collects the data, and then loads the next page. The background script should hold the results until all the pages have been loaded.</p>