Search code examples
javascriptajaxgreasemonkeysynchronousgm-xmlhttprequest

How to make synchronous AJAX calls in greasemonkey?


I have a list of URLs and need to load each page, one after another.
This is my main function that i have in my Mind.

mainFunction() {  
loop {  // Loop through URL list
oPage = func1(URL); //Get page contents
aResult = func2(oPage); //Analyse the contents
func3(aResult); //Do current page modifications
}  
}

func1 uses GM_xmlhttprequest, which is asynchronous, so oPage results in 'underfined' as function ends BEFORE the contents of a page could be retrieved.
func2 also uses GM_xmlhttprequest, so even no matter if oPage was undefined, aResult will be undefined too.

Any ideas on how to make all of this work?

func1 func2 and func3 should be reusable throughout the script, each of these functions may be used independently or together in different parts of script.


Solution

  • var urls = [];
    
    (function recursive(list)
    {
        if (list[0])    // the list is not empty
        GM_xmlhttpRequest({ // that would be "func1"
            "url" : list[0],    // first url in the list
            "onload" : function(xhr)
            {
                var oPage = xhr.responseText,   // page contents
                aResult = func2(oPage); // analyse the contents
                func3(aResult); // do current page modifications
    
                list.shift();   // remove the first link of the list
                recursive(list);    // go to the next url in the list
            }
        });
        else
        alert("end of list");
    })(urls);
    

    haven't tested it but you got the idea