title: Passing a message from content script to Angular JS based Chrome Extension
body: <p>I am trying to get a successfully injected content script to send a message to the injecting AngularJS-based Chrome extension.</p>
  
  <p>The injecting controller method looks like this:</p>
  
  <pre><code>$scope.selectElement = function() {
    // Close the extension window
    window.close();
  
    window.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"});
      }
    );
  
    // Send content script to web page
    window.chrome.tabs.executeScript(null, { file: 'app/bower_components/jquery/jquery.js' }, function() {
      window.chrome.tabs.executeScript(null, { file: 'app/scripts/libs/dom_selector.js' });
    });
  };
  </code></pre>
  
  <p>The injected script calls the following once the page is clicked:</p>
  
  <pre><code>$(document).click(function(event) {
    console.log($(event.target));
    chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
      console.log(response);
    });
  });
  </code></pre>
  
  <p>This fires (the first log message appears in the console), but the second log message just prints <code>undefined</code>.</p>
  
  <p>I thought maybe the <code>window.close()</code> might be the issue, but the <code>window.chrome.tabs.executeScript</code> calls are working fine, so I'm not sure why the event listener isn't firing. Is it in the wrong place? I have a feeling it is, since I should really only be declaring it once somewhere, right? If it is in a controller like this it'll get set up each time the method is run and then each listener will respond to an event, causing the event response to be sent many times. Is this correct?</p>
  
  <p>Any AngularJS guidance on this is most welcome...</p>