2

This is my GM_xmlhttpRequest script:

// ==UserScript==
// @name        test
// @namespace   test
// @include     http://stackoverflow.com/*
// @version     1
// ==/UserScript==

GM_xmlhttpRequest({
  method: "GET",
  url: "http://example.com",
  onload: function(response) {
    alert(response.responseText);
  }
});

function begin(){
    alert("ready");
}

$(document).ready(function() {
    begin();
}); 

Which alerts only the contents of example.com, not "ready".

BUT when I do the following nothing happens - there are no alerts whatsoever:

function begin(){
    GM_xmlhttpRequest({
      method: "GET",
      url: "http://example.com",
      onload: function(response) {
        alert(response.responseText);
      }
    });
    alert("ready");
}

$(document).ready(function() {
    begin();
}); 

What am I doing wrong?

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
Yeti
  • 5,628
  • 9
  • 45
  • 71
  • 2
    Just realized having **// @grant none** in the script descriptor blocks GM_xmlhttpRequest from executing. – Yeti Jan 03 '13 at 11:24

1 Answers1

3

I'm pretty sure that the first example shows the contents returned by GM_xmlhttpRequest, but not the "ready"

jQuery/$ is not accessible directly within Greasemonkey. It's loaded inside the page(by stackoverflow.com in this case). To access functions/properties of the page you may use the unsafeWindow-object( http://wiki.greasespot.net/UnsafeWindow ):

unsafeWindow.$(document).ready(function() {
    begin();
}); 

But I would suggest to call begin() directly, you don't need $.ready() here, because GM-scripts will always execute when the DOMContentLoaded-event fires, which is equal to $.ready()

Dr.Molle
  • 116,463
  • 16
  • 195
  • 201
  • You are right, the first example doesn't print "ready". My bad. I was testing between alerts and maybe imagined both alerts showing up! Just calling begin() worked. Thanks! – Yeti Jan 02 '13 at 13:28