title: Making Chrome Extension background function synchronous
body: <p>Updated: this is @ViewSource solution which is correct, except you need a return true in background.js as shown.</p>
  
  <p>I have a problem in my chrome extension design which I cant find a fix for no matter how many ways I configure it.</p>
  
  <p>In my popup.js I have a button a button click event like this:</p>
  
  <pre><code>document.getElementById('btnUpload').addEventListener('click', function() {
  
      sendDocMsg(windowUrl);
  
  });
  
  }
  
  function sendDocMsg() {
  
      chrome.runtime.sendMessage({url: decodeURIComponent(windowUrl)},     
      function(response){
          currentHTML = response.data;
  
   });
  </code></pre>
  
  <p>and in the background I have a handler for this:</p>
  
  <pre><code>chrome.runtime.onMessage.addListener(function(message, sender, sendResponse)    {
       var url= message.url;
       var doc = null;
       script = getScript(url);
       if(script!=null) {
          chrome.tabs.query({active: true, currentWindow: true},     function(tabs){
             chrome.tabs.sendMessage(tabs[0].id, {action: "getDocument", data:script}, 
                 function(response) {
                    doc=response.data;
                    sendResponse({data: doc});
             });  
          });
       }  
  return true;           
  </code></pre>
  
  <p>});</p>
  
  <p>which should send the data from the content page back to popup.js (via background page), but for some reason, I'm getting: </p>
  
  <pre><code>Error in event handler for (unknown): TypeError: Cannot read property 'data'     of undefined
  at chrome-extension://kpcmhhlcnclcnahkpjpaejaccponfble/popup.js:125:31
  </code></pre>
  
  <p>I have set a breakpoint in the background, and the correct data is being set on the response. I initially had a function call from popup to background using 
      chrome.extension.getBackgroundPage()</p>
  
  <p>becuase I read that this was the preferred way for popup to contact background, but this caused other issues.</p>
  
  <p>Can anyone see why the data would be returned to popup.js please?</p>