title: Chrome Extension message passing: Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist
body: <p>My chrome extension has the following two javascripts:</p>
  
  <p><code>background.js</code>, running as background script: </p>
  
  <pre><code>chrome.runtime.onMessage.addListener(function(message, sender, sendResponse) {
      if (message.data == "takeScreenshot") {
          var resp = sendResponse;
          chrome.tabs.captureVisibleTab(function(screenshotUrl) {
              resp({
                  screenshot: screenshotUrl
              });
          });
          return true; // Return true to tell that the response is sent asynchronously
      } else {
          return "TestReply";
      }
  });
  </code></pre>
  
  <p><code>api.js</code>, running as web accessible resource:</p>
  
  <pre><code>window.takeScreenshot = (function() {
      var isTakingScreenshot = false; // Semaphore
      return function() {
          if(isTakingScreenshot) return Promise.reject();
          isTakingScreenshot = true;
          return new Promise(function(resolve, reject) {
              chrome.runtime.sendMessage("eomfljlchjpefnempfimgminjnegpjod", "takeScreenshot", function(response) {
                  console.log(response);
                  isTakingScreenshot = false;
                  resolve(response.screenshot);
              });
          });
      }
  })()
  window.test = (function() {
      return function() {
          return new Promise(function(resolve, reject) {
              chrome.runtime.sendMessage("eomfljlchjpefnempfimgminjnegpjod", "test", function(response) {
                  console.log(response);
                  resolve(response.length);
              });         
          });
      }
  })();
  </code></pre>
  
  <p>When I execute in a tab's console either function (auto-complete knows them, so they are available), I get the error:</p>
  
  <blockquote>
    <p>Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.</p>
  </blockquote>
  
  <p>and the respone returned is undefined.</p>
  
  <p>I have checked that the id in <code>sendMessage</code> is the same as in the manifest and in the chrome://extensions page, and I have opened the background page DevTools of the extension and manually added the same listener there to make sure the listener is indeed registered.</p>
  
  <p>My searches found that this error means the listener has not been correctly registered, but I don't find the underlying reason. Do you have an idea what causes this error?</p>