Question

I am trying to get a successfully injected content script to send a message to the injecting AngularJS-based Chrome extension.

The injecting controller method looks like this:

$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' });
  });
};

The injected script calls the following once the page is clicked:

$(document).click(function(event) {
  console.log($(event.target));
  chrome.runtime.sendMessage({greeting: "hello"}, function(response) {
    console.log(response);
  });
});

This fires (the first log message appears in the console), but the second log message just prints undefined.

I thought maybe the window.close() might be the issue, but the window.chrome.tabs.executeScript 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?

Any AngularJS guidance on this is most welcome...

Was it helpful?

Solution

It was the window.close() that broke it. Annoying, since I need to close the popup so the user can select any HTML element on screen. But I can confirm that removing that line allowed me to get a response from the listener.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top