1

The issue that I'm facing is quite interesting. I've set up the communication between my background and my popup, it works perfectly fine, until I'm trying to reach the data in the chrome.tabs.query callback.

Could you please advise what could have went wrong?

background.js

chrome.extension.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.greeting === 'getTabs') {
      chrome.tabs.query({},function(tabs){
        sendResponse(tabs);
      });
    }

    if (request.greeting === 'test') {
      sendResponse('test-string');
    }
});

popup.js

$(document).ready(function(){
  $('button').on('click', function(){
    chrome.extension.sendMessage({greeting: 'getTabs'}, function(response){
      console.log(response);
    });
    chrome.extension.sendMessage({greeting: 'test'}, function(response){
      console.log(response);
    });
  });

});

I debugged the background.js part, and I get the arra of tabs, but for some reason it's not getting sent as the response, even though the sendResponse(tabs) is in the callback function. Further addition, if I set a static string, like 'apple', it will not send it either.

Gregion
  • 307
  • 3
  • 11

1 Answers1

1

I found the answer to my question eventually, although I can't quite comprehend, why did it solve the problem.

background.js

chrome.extension.onMessage.addListener(
  function(request, sender, sendResponse) {
    if (request.greeting === 'getTabs') {
      chrome.tabs.query({},function(tabs){
        sendResponse(tabs);
      });
    }

    if (request.greeting === 'test') {
      sendResponse('test-string');
    }
    return true;
});

I had to return true, else the port in the chrome messaging.js was null.

Gregion
  • 307
  • 3
  • 11
  • 2
    It's a [documented feature](https://developer.chrome.com/extensions/runtime#event-onMessage). – wOxxOm Jul 18 '17 at 20:34