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.
November 19th, 2009 - 13:17
Thank you! This works great.
November 19th, 2009 - 18:48
No prob, glad you liked.