-1

Before everyone finds it, this has more or less been asked before: Load remote URL with Greasemonkey and jQuery

However, it was 3 years ago. I tried the various methods presented in the answers and none of them work.

Basically, my problem is this: I'm writing a greasemonkey script that, for right now, is supposed to A) grab a link on a page, B) request the page the link is linking to (it's on the same host), and C) find a certain value on that page. I'm using jQuery 1.7.2 and the latest version of Greasemonkey to try to accomplish this.

The problem is that though I can successfully request the page, I can't do anything with the response. I've tried assigning the response to a variable outside of the callback, but it ends up empty. I've tried appending the response html to a div I inserted on the page, but using console.log on the div shows that it's empty (even though firebug actually shows the html). It's like as soon as the callback ends, the html that was retrieved not only doesn't exist, but didn't ever exist.

So basically, I want to ask how to retrieve the html so that I can actually use it after the request is finished. Here's what I've got right now (I've deleted aforementioned attempts to append the response to a div on the page):

function getLink(url){
    var resp;
    GM_xmlhttpRequest({
        method: 'GET',
        url: url,
        onload: function(response){
            resp = response.responseText;
        }
    });
    console.log(resp) //nothing here...

    //failed code :(
    /*$.ajax(url, {success: function(data){resp = data})
    console.log(data)*/
}

What magic code do I need to write to get the above to work as intended?

Community
  • 1
  • 1
G. Martin
  • 163
  • 1
  • 7

1 Answers1

0

GM_xmlhttpRequest() operates asynchronously by default. That means that the onload fires long after the console.log(resp) //nothing here... line.

Although GM_xmlhttpRequest() now takes a synchronous: true parameter, it is very buggy and I do not recommend trying to use it, for now.

The correct way to do things (and better programing and UI practice) is put everything in the onload handler:

function getLink (url) {
    GM_xmlhttpRequest ( {
        method: 'GET',
        url: url,
        onload: function (response) {
            var resp = response.responseText;
            console.log (resp);

            // DO EVERYTHING THAT REQUIRES resp HERE.
        }
    } );
}

This may require changing how you think about certain operations, but it is well worth it.

Community
  • 1
  • 1
Brock Adams
  • 90,639
  • 22
  • 233
  • 295