title: Sending message from popup.js in Chrome extension to background.js
body: <p>What is the proper way to send a message (and get a response) to background.js from popup.js in a Chrome extension? Every method I try ends up with an error that:</p>
  
  <p>"Port: Could not establish connection. Receiving end does not exist."</p>
  
  <p>I would prefer to use chrome.extension.sendMessage() over chrome.extension.connect() with port.postMessage(), but neither method seems to have worked.</p>
  
  <p>What I am trying to do is wire a button in the popup.html to call into some javascript in popup.js which calls back to background.js in an effort to get info about the currentTab() that was topMost (ie:to get the current URL string to show in the popup.html)</p>
  
  <p>Right now in <strong>popup.js</strong> (wired to the action of the button) I have:</p>
  
  <pre><code>function getURL()
  {
     chrome.extension.sendMessage({greeting: "GetURL"}, 
            function(response) { tabURL = response.navURL });
  
     $("#tabURL").text(tabURL);
  }
  </code></pre>
  
  <p>In <strong>background.js</strong> I have:</p>
  
  <pre><code>chrome.extension.onMessage.addListener( function(request,sender,sendResponse)
  {
      if( request.greeting == "GetURL" )
      {
          var tabURL = "Not set yet";
          chrome.tabs.getCurrent(function(tab){
              tabURL = tab.url;
          });
  
          sendResponse( {navURL:tabURL} );
      }
  }
  </code></pre>
  
  <p>Any ideas?</p>