1

I am trying to send a url from content.js to background.js to make an ajax request there.

In content.js I have the following code. By the way, this message sending from content.js to background.js works and I have tested it. But the problem is that I am getting no response from background.js back. I have also tested that ajax request was made successfully.

$(document).on('click', '.readmore a', function(event) {
    event.preventDefault();
    var link = $(this).attr('href');

    chrome.runtime.sendMessage(extractFacebookUrl(link), function(response){
        console.log(response); //nothing get consoled out here.
    });
});

In background.js, I have the following code.

chrome.runtime.onMessage.addListener(function(url, sender, response){
    $.get(url, function(data){
        obj = {'data' : data, 'link' : url}
        //alert(data); //This alert shows that ajax request was successful.
        response(obj); //But this returns nothing to content.js. Why?
    });
});
Eloims
  • 5,106
  • 4
  • 25
  • 41
Zip
  • 5,372
  • 9
  • 28
  • 39
  • By the way, "code snippets" are for complete code only. Chrome extensions use chrome api's, and so aren't complete. This makes the snippet useless. – Teepeemm Nov 09 '15 at 22:33

1 Answers1

3

From https://developer.chrome.com/extensions/runtime#event-onMessage about the sendResponse function.

[...] This function becomes invalid when the event listener returns, unless you return true from the event listener to indicate you wish to send a response asynchronously (this will keep the message channel open to the other end until sendResponse is called).

You need to return true from the event handler you attached to chrome.runtime.onMessage.

Your code in background.js would then look like:

chrome.runtime.onMessage.addListener(function(url, sender, response){
    $.get(url, function(data) {
        response({'data' : data, 'link' : url});
    });
    return true;
});
Eloims
  • 5,106
  • 4
  • 25
  • 41
  • You saved my day! Have been sitting with this one for hours :D Care to explain the text in bold for my case? I am not quite getting it. – Zip Nov 09 '15 at 18:06
  • 1
    @Zip Depends, do you understand how async javascript works? But in principle, Chrome needs to decide what to do with the request before the listener stops executing - so that the sender will be notified that the message was processed, in case you don't want to return anything. The only way to let Chrome now "I will use `response` but later, hold the line" is to return true, otherwise it will reply to sender "Ok, received, no data for response". – Xan Nov 10 '15 at 12:37