Exception
Exception

Reputation: 8379

Why this function is returning response as null

I wrote a function on event click as below

$('#ClickMe').live('click', function () {
    chrome.extension.sendRequest({ method: "getT" }, function (response) {
        alert(response.data); // Displaying undefined..
    });
});

in background page..

function wish(){      
   return "Hey...";
}
chrome.extension.onRequest.addListener(function(request, sender, sendResponse){
  if (request.method == "getT"){
    sendResponse({data: wish()});
  }
  else
    sendResponse({});
});

I cannot get the response in Content Script.Please help me on this.

Upvotes: 0

Views: 167

Answers (1)

Mohamed Mansour
Mohamed Mansour

Reputation: 40169

You cannot send functional parameters like that within a JSON object you would need to instantiate it first, and then pass it as a variable not as a function because it will treat it as a Closure, so when it does the serialization, it will not include that.

function wish(){      
   return "Hey...";
}
chrome.extension.onRequest.addListener(function(request, sender, sendResponse){
  if (request.method == "getT"){
    var data = wish();
    sendResponse({data: data});
  }
  else
    sendResponse({});
});

The above snippet should work.

Upvotes: 1

Related Questions