1

I am working on a chrome extension. I am using chrome.runtime.sendMessage() API to send a URL to another js file. When I receive the URL in other file through chrome.runtime.onMessage.addlistener(function(sent,sender,sendResponse){...}). I call another method or function checkUrl(url){...} to which I pass the URL sent by the other file as a message. and this function returns the Ajax call to that URL. And then I use .then() promise in the scope where I have called the checkUrl(url){...} function. I get the response perfectly and after displaying the response in the console, I send that response back to the sender file where I got the message from. But I am not getting any response on the content script I don't know if I have mistaken something...

Content Script Code to send Message

chrome.runtime.sendMessage({type:"postUrl",mess:url},function(r){
   console.log(r.res);
});

Script I am getting the message and then trying to send response back

chrome.runtime.onMessage.addListener(function(sent,sender,sendResponse){
 alert("message recieved");
 var str;
 switch(sent.type){
  case "postUrl":{
        checkUrl(sent.mess).then(function(r){
           console.log("Promise Test : " + r);
           sendResponse({res:r})
     });
     break;
  }
 }
});


function checkUrl(url){
    return $.ajax({
       method:"GET",
       url:"http://www.bitbaysolutions.com/connections.php?fbPostUrl=true",
       data:{
        url:url
       }
    })

}
Nadeem
  • 145
  • 1
  • 13
  • You are not returning a value in checkUrl. The jQuery ajax is asynchron and you can not use it to send a response like that. Your ajax function should have a complete callback function, that uses sendMessage itself to send data back to your first script. – D B Sep 29 '17 at 11:42
  • How would I do that, do you have any reference ! – Nadeem Sep 29 '17 at 11:45
  • Also this code is not valid `{type:"postUrl",mess:url},` what is `mess` and `url`? – jukben Sep 29 '17 at 11:46
  • @jukben I am just passing a JSON object as a message – Nadeem Sep 29 '17 at 11:47
  • @Nadeem Extend your ajax call with a `success` property: `$.ajax({..., success: function(result) {chrome.runtime.sendMessage(result)});`. In your first script, you have to add a chrome.runtime.onMessage.addListener to handle the message send once he ajax finished. – D B Sep 29 '17 at 11:51
  • @DB the first script is wrote inside another function which get called by another function so even if I put the listener script inside that, I will require to call that function and that is not possible – Nadeem Sep 29 '17 at 12:50
  • 1
    Possible duplicate of [Chrome Extension Message passing: response not sent](https://stackoverflow.com/questions/20077487/chrome-extension-message-passing-response-not-sent) – wOxxOm Sep 29 '17 at 13:15
  • Thank you so much @wOxxOm it worked for me ! – Nadeem Sep 29 '17 at 13:29

0 Answers0