GreaseMonkey: GM_xmlhttpRequest return value to calling function

别来无恙 提交于 2019-12-24 08:46:39

问题


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.


回答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.



来源:https://stackoverflow.com/questions/7196772/greasemonkey-gm-xmlhttprequest-return-value-to-calling-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!