title: Intercepting XMLHttpRequest in Greasemonkey while using @grant the right way
body: <p>So my goal was to hijack all <code>XMLHttpRequest</code> responses and do something with them in my script's scope. But since I <code>@grant</code> something I <s>had to use <code>unsafeWindow</code></s> couldn't do it easy way. (I don't know why, but I couldn't change <code>unsafeWindow.XMLHttpRequest.prototype.open</code>. There was no error, but <code>XMLHttpRequest</code> didn't work at all.) So I ended up with this piece of code:</p>
  
  <pre><code>// ==UserScript==
  // @name        a
  // @include     *
  // @version     1
  // @grant       GM_xmlhttpRequest
  // ==/UserScript==
  
  realProcess = function(xhr) {
      // do something
  }
  
  function hijackAjax(process) {
      if(typeof process != "function") {
          process = function(e){ console.log(e); };
      }
      window.addEventListener("hijack_ajax", function(event) {
          process(event.detail);
      }, false);
      function injection() {
          var open = XMLHttpRequest.prototype.open;
          XMLHttpRequest.prototype.open = function() {
              this.addEventListener("load", function() {
                  window.dispatchEvent(new CustomEvent("hijack_ajax", {detail: this}));
              }, false);
              open.apply(this, arguments);
          };
      }
      window.setTimeout("(" + injection.toString() + ")()", 0);
  }
  hijackAjax(realProcess);
  </code></pre>
  
  <p>My question is: can it be done better/faster/more elegant?</p>
  
  <p><strong>EDIT:</strong> Updated code according to hints.</p>