title: Chrome extension tabs sendMessage from background to contentscript errors
body: <p>contentscript.js</p>
  
  <pre><code>chrome.runtime.onMessage.addListener(
    function(request, sender, sendResponse) {
      console.log(sender.tab ?
                  "from a content script:" + sender.tab.url :
                  "from the extension");
      if (request.greeting == "hello")
        sendResponse({farewell: "goodbye"});
    });
  </code></pre>
  
  <p>background.js</p>
  
  <pre><code>chrome.browserAction.onClicked.addListener(function(tab) {
      chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
          chrome.tabs.sendMessage(tabs[0].id, {greeting: "hello"}, function(response) {
              console.log(response.farewell);
          });
      });
  });
  </code></pre>
  
  <p>This sometimes works, and sometimes doesn't.</p>
  
  <p>Cases that don't work:</p>
  
  <p>1) When I reload the extension and click the extension icon on an existing tab
  2) When I add a breakpoint inside background.js</p>
  
  <p>Cases that do work:</p>
  
  <p>1) When I reload the extension and reload/load new tab and no breakpoints are added inside background.js</p>
  
  <p>The errors thrown are usually:</p>
  
  <pre><code>Port: Could not establish connection. Receiving end does not exist. lastError:29
  Error in event handler for 'undefined': Cannot read property 'farewell' of undefined TypeError: Cannot read property 'farewell' of undefined
  at chrome-extension://glbcapgiojbbnjhngjdmoglaamjbjjak/background.js:16:28
  at &lt;error: illegal access&gt;
  at Event.dispatchToListener (event_bindings:356:21)
  at Event.dispatch_ (event_bindings:342:27)
  at Event.dispatch (event_bindings:362:17)
  at Object.chromeHidden.Port.dispatchOnDisconnect (miscellaneous_bindings:258:27) 
  </code></pre>
  
  <p>Can anybody shed some light on this? I find it particularly strange that breakpoints would cause it to fail (almost as if pausing background.js will cause the event listener to die)</p>