user971637
user971637

Reputation:

wait for chrome.extension.sendRequest

I want to read my global variable from background.html , and I use this:

chrome.extension.sendRequest()

I run this code in my timer function... and everytime it return me undefined. If I put a alert message in above function then it show me my variable.. if I'm not using alert() then it is undefined. So how can I wait above function to return correct value,... as I understand I need to wait for response... but how can I do it right, I tried to use setInterval inside above function and not help me. How can I read my global value from background.html... I need a piece of code.

chrome.extension.sendRequest({cmd: "myvalue"}, function(response) {
     myglobalvalue = response;
  if(response==1){

   alert("response: "+response); // alert show me right value

             }
});

if(myglobalvalue)doFunc();  //myglobalvalue is undefenited

Upvotes: 0

Views: 715

Answers (3)

jjNford
jjNford

Reputation: 5270

Here you go: Chrome Extension Socket

I build this to provide continuous 2 way communication between a popup and background page. The "How To Use" section tell you what to do. Just include socket.js in your popup and background page, the connection will be created automatically for you.

Just use:

Socket.postMessage(namespace, literal, method, [args]);

This will allow you to trigger functions that can callback with data.

Upvotes: 0

abraham
abraham

Reputation: 47833

chrome.extension.sendRequest accepts a callback function that will fire with the response data.

chrome.extension.sendRequest({ data: 'send data' }, function(response) {
  console.log(response);
  // the var has been returned and you can use it here or call another function.
});

Upvotes: 0

Marius
Marius

Reputation: 101

You can read variables from background.html with chrome.extension.getBackgroundPage().varname

Upvotes: 1

Related Questions