javascriptajaxgreasemonkeygm-xmlhttprequest

GM_xmlhttpRequest does not work when called from inside $(document).ready()?


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?


Solution

  • 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()