1

ive been messing round with this for hours and im pulling my hair out at it. How do I return var a from myFunction to allow it to be set as var b which and then display the value of b in the alert message? Thanks! :)

function myFunction(arg)
{
var a;

GM_xmlhttpRequest({
  method:"GET",
  url:"http://site.com/arg?" + arg,
  headers:{
    "User-Agent":"monkeyagent",
    "Accept":"text/monkey,text/xml",
    },
  onload:function(details) {
    a = details.responseText;


  }
});

return a;

}

b = myFunction("blabla");
alert(b);

When I tried it returned just a blank message.

James Stevenson
  • 99
  • 1
  • 1
  • 6

1 Answers1

1

You can't return a like that because GM_xmlhttpRequest operates asynchronously.

The onload function will fire long after myFunction has returned. Anything that you want to do with a will have to be done from functions called within the onload function.

Greasemonkey just added support for synchronous mode, starting with version 0.9.9. If you must, you can download the prerelease of version 0.9.10, here.

However, you would be smart to learn to handle this kind of thing asynchronously. You will get a faster, more responsive UI instead of "hangs" and "freezes". It's a good concept to grok for all manner of real-life programming situations.

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
  • so how to return a for use outside the xmlrequest? – 龚元程 May 22 '12 at 02:57
  • @龚元程, you would use code like [this question](http://stackoverflow.com/q/8778267/331508) -- except that last I checked, bugs in Greasemonkey keep it from working. It's better to not code that way at all. – Brock Adams May 22 '12 at 21:15