I tried:
GM_xmlhttpRequest({
method: "GET",
url: "...",
onload: function(response) {
r = response.responseText;
}});
alert(r); //undefined
How do this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Why this is happening
By default, ajax requests using XMLHTTPRequest are asynchronous. This means that the call to method returns immediately and the main execution continues while the request proceeds in the background. When the request completes, the callback method will be invoked with the results of the request. Thus, your alert is executed before the (asynchronous) request ever completes.
Solution 1: Callbacks
You haven’t provided context as to why you’d need the response text synchronously so it’s possible you could rewrite your code to use callbacks and continue using the asynchronous behaviour – this is usually good practice.
Solution 2: Force synchronous requests
However, if find that you absolutely must make requests synchronously, you’ll find that you can request that the ajax request be made synchronously. With Greasemonkey, you should use the option
synchronous: truewhen invokingGM_xmlhttpRequest, as documented here. Note that the docs say thatWith XHR objects in the browser, you’d achieve the same results by passing
falseas the second parameter toXMLHTTPRequest#open.If you’re working with an older version of Greasemonkey, the answers to this SO question might prove useful: How to make synchronous AJAX calls in greasemonkey?