1

I'm having a problem with sending a response back to the content.js page from the background.js page.

On my content.js page I have:

chrome.runtime.sendMessage({auth: 'test'}, function(response){
     console.log(response.auth);
});

And on my background.js page I have:

chrome.runtime.onMessage.addListener(function(request,sender,sendResponse){

  if(request.addressToCopy){
        copy(request.addressToCopy);
    }

    if(request.auth == 'test'){
        chrome.storage.local.get(['access_token', 'refresh_token'], function(results){
            $.get('https://coinbase.com/api/v1/account/balance', {access_token: results['access_token']}, function(data){
                sendResponse({auth: 'pass!'});
            }).fail(function(){
                sendResponse({auth: 'fail!'});

            });
        }); 
    }
});

My problem is: sendResponse doesn't work where it is in the code above. I won't get any error, it's just that content.js won't console.log anything. If I put the sendResponse OUTSIDE the if statement (so its directly a child of onMessage.addListener) it works, my content.js script will output "pass" or "fail". But it will not work how I have it. Why is that?

Shivang Saxena
  • 195
  • 1
  • 2
  • 13
  • possible duplicate of [Two way communication is returning error in Chrome Extension](http://stackoverflow.com/questions/16419563/two-way-communication-is-returning-error-in-chrome-extension) – Rob W Mar 16 '14 at 09:01
  • possible duplicate of [Chrome Extension Message passing: response not sent](http://stackoverflow.com/questions/20077487/chrome-extension-message-passing-response-not-sent) – Teepeemm Sep 28 '15 at 19:32

1 Answers1

2

You must return true in your event listener to keep the message channel open to the content script until sendResponse is called. Returning true indicates the response will be sent asynchronously

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
     ...
     $.get(url, payload, function(data) {
          sendResponse(response)
     })
     return true;
});
gtria
  • 72
  • 4