The non-standard behavior of GM_xmlhttpRequest has annoyed to no end
recently so I came up with the following. With this code you can use the
standard MooTools Request object instead of GM_xmlhttpRequest, and it
transparently uses GM_xmlhttpRequest as the underlying transport if
available. With this piece of code you can keep the GM specific aspects of
your code base to a minimum.
This isn't super well tested, but it already works well enough for me. If
people find it useful, I'll put it into a repo and accept bug fixes.

http://gist.github.com/158725

Browser.Request = function(){
  return $try(function(){
    return new GM.Request();
  }, function(){
    return new XMLHttpRequest();
  }, function(){
    return new ActiveXObject('MSXML2.XMLHTTP');
  });
};

var GM = {};

GM.Request = new Class({

  name: "GM.Request",

  initialize: function(force)
  {
    if(!GM_log && !force)
    {
      throw Error();
    }
    this.headers = {};
  },


  __onreadystatechange__: function(responseDetails)
  {
    this.status = responseDetails.status;
    this.statusText = responseDetails.statusText;
    this.responseHeaders = responseDetails.responseHeaders;
    this.responseText = responseDetails.responseText;
    this.readyState = responseDetails.readyState;
    if(this.onreadystatechange && $type(this.onreadystatechange) ==
'function') this.onreadystatechange();
  },


  open: function(method, url)
  {
    this.method = method;
    this.url = url;
  },


  setRequestHeader: function(key, values)
  {
    this.headers[key] = value;
  },


  getResponseHeader: function(key)
  {
    return this.responseHeaders[key];
  },


  send: function(data)
  {
    GM_xmlhttpRequest({
      method: this.method,
      url: this.url,
      headers: this.headers,
      data: data
      onreadystatechange: this.__onreadystatechange__.bind(this)
    });
  }
});

Reply via email to