Shivang Saxena
Shivang Saxena

Reputation: 195

Chrome extension - sendMessage doesn't work unless directly below listen function?

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?

Upvotes: 1

Views: 300

Answers (1)

gtria
gtria

Reputation: 72

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

Upvotes: 2

Related Questions