0

I am making a chrome extension and in my extension I am sending message from content script to background script.

chrome.runtime.onMessage.addListener(
  function triggerNew(request) {
    if (request.method == "addNew") {
      //alert("in content script");
      var x=startClick();
      chrome.runtime.sendMessage({name: "Response" , data : x});
    }
  }
);

`function startClick(){
document.addEventListener('click', function(e){
var target = e.target || event.srcElement;
return target;
}`

I have called a function startClick in my content script, but Response message is getting sent before startClick executes.

How to make it send the data I get in variable x from startClick function?

Alexander Farber
  • 21,519
  • 75
  • 241
  • 416
Abhishek Tripathi
  • 1,211
  • 2
  • 15
  • 30
  • 1
    Almost certainly a [duplicate of this](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) but the question is missing the `startClick` function. – Quentin Mar 14 '16 at 10:43
  • i went through that link but could not understand much. may you tell me how to achieve it here ? @Quentin – Abhishek Tripathi Mar 14 '16 at 10:50
  • Statements do not get reordered. statClick gets called before sendMessage. I suspect you do somethin asynchronous inside startClick, show us some more code. – Tamas Hegedus Mar 14 '16 at 10:52
  • @Ram — No, because, as I said, your question is missing most of the relevant code. – Quentin Mar 14 '16 at 10:54

1 Answers1

1

I don't think startClick is called after chrome.runtime.sendMessage, the problem is in your usage of the callback method.

You callback method's signature must look like this:

function(any message, MessageSender sender, function sendResponse) {...};

To send a response to a call to chrome.runtime.onMessage.addListener, you must use the sendResponse function as indicated here in the doc: https://developer.chrome.com/extensions/runtime#event-onMessage

Important note: As indicated in the doc (make sure you read it all), your callback function must return true in order to keep the sendResponse function valid. This is essential if you want to call sendResponse from an asynchronous function.

Edit: try this

background:

chrome.runtime.onMessage.addListener(
    function triggerNew(request, sender, sendResponse) {
        if (request.method == "addNew") {
            var x = startClick();
            sendResponse({
                data: x
            });
        }
    }
);

content script:

chrome.extension.sendMessage({method: 'addNew'} , function(response) {
    alert(response.data);
});
François F
  • 144
  • 1
  • 5