occasionally useful ruby, ubuntu, etc

1Jan/094

Accessing GM_xmlhttprequest from event handlers bound by jQuery

So I like jQuery. And I like Greasemonkey. I especially like the ability of Greasemonkey's ajax calls to go cross-domain. But how do I get access to this functionality in my event handlers? Calling GM_xmlhttprequest in a method that doesn't execute while the Greasemonkey sandbox is still alive doesn't work. At first I didn't think it was possible, but I discovered a way...using setInterval.

So here's the problem. You want something like this:

$(function(){
  $("a").click(function(){
    GM_xmlhttprequest({url: "http://www.google.com/", method: 'GET'});
  });
});

or something, right? But that doesn't work because by the time the $'s DOM ready event fired, Greasemonkey is gone. So what do you do? Well...keep Greasemonkey around, but in a limited capacity. Okay okay, here's the code:

var ajaxQueue = [];
var processAjaxQueue = function(){
  if (ajaxQueue.length > 0) {
    for (ajax in ajaxQueue) {
      var obj = ajaxQueue[ajax];
      // http://diveintogreasemonkey.org/api/gm_xmlhttprequest.html
      GM_xmlhttpRequest(obj);
    }
    ajaxQueue = [];
  }
}
setInterval(function(){
  processAjaxQueue();
}, 100);
 
function gmAjax(obj){
  ajaxQueue.push(obj);
}

So now you call gmAjax instead of GM_xmlhttprequest (with the same argument) and it'll get fired off within the next 100ms. Neat huh? And if you're worried about security (which you should be) -- I've tested this myself, and gmAjax isn't acccessible anywhere outside of the Greasemonkey sandbox. Huzzah, mission accomplished.

Comments (4) Trackbacks (0)
  1. Thank you! This works great.

  2. Thanks! I’ve just spent all my day long trying to figure out why GM_xmlhttprequest didn’t work when I use jQuery… Now I’ve got my answer AND a fix :-)

    Thanks again! l

  3. I don’t understand why we are required to do this, the functions is still there “alert(GM_xmlhttpRequest);” but this works, thanks


Leave a comment


No trackbacks yet.