views:

71

answers:

4

Hello,

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.

+1  A: 

Normally you would put the calls inside of the xmlhttprequest's response handler, such that it returns immediately, and when it does get that page it then executes the required code.

If you really need to make them happen in a specific order, you can make the return for the first call the second, etc.

zebediah49
+1  A: 

Is there any reason why you need to use Greasemonkey specific functionality? Are you doing cross site requests or something that specifically requires it? Looking at the Wiki for Greasemonkey, I can't find the option to set asynchronous to false.

Your easiest option is to include JQuery with your Greasemonkey script and use JQuerys AJAX functionality. Ofcourse, this can be done without JQuery, however, cross browser incompatibility in this area is quite the pain to handle manually.

Using JQuery, your code would look something like this:

function func1(url) {
    var result;

    $.ajax({
        type: "GET",
        url: url,
        async: false,
        success: function(data){
            result = data;
        }
    });
    return result;
}

and you would declare your variable oPage like this:

var oPage = func1(url);

The rest I think you can figure out yourself, good luck.

Anders
A: 

Check out the solution from here - it may help you with what you need.

A: 
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

w35l3y