1

I have a problem using xmlHttpRequest and sendResponse at the same time.

I don't know why but when I set my variable in the x.onload, I get the response "undefined", if I set the variable outside the x.onload, I get the correct value.

See an example of my code below:

content scrypt :

chrome.runtime.sendMessage({MessageTest: "something"}, function(response) {alert(response.msg);});

event page :

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
   var tableauTest = [];

   var x = new XMLHttpRequest();
   x.open('GET', 'http://monsite/page.php');
   x.onload = function() {
       tableauTest[1] = "test"; // not working here

   };
   // if a put tableauTest[1] = "test"; here, it's working
   x.send();
    sendResponse({
       msg: tableauTest[1]
   }); 
 });

I tried to put return true; (like here) but it doesn't seem to work for me

Community
  • 1
  • 1
Meta
  • 11
  • 2
  • Yes, you tried. You have another conceptual error here with async code: https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron You need to move `sendResponse` inside `onload` as well. – Xan Dec 15 '15 at 11:52
  • Please note: I have re-closed the question with another duplicate, as it seems to be your main problem. But you should still take http://stackoverflow.com/questions/20077487/chrome-extension-message-passing-response-not-sent in consideration: to call `sendResponse` asynchronously you need to return true. – Xan Dec 15 '15 at 15:59
  • thank you very much! it's working, I needed both, return true and put sendResponse inside onload – Meta Dec 15 '15 at 16:10

0 Answers0