开发者

GreaseMonkey: GM_xmlhttpRequest return value to calling function

开发者 https://www.devze.com 2023-03-30 16:02 出处:网络
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 mes

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消