Подтвердить что ты не робот

Как перехватить XMLHttpRequests из Greasemonkey script?

Я хотел бы захватить содержимое запросов AJAX, используя Greasemonkey.

Кто-нибудь знает, как это сделать?

4b9b3361

Ответ 1

Принятый ответ почти правильный, но он может немного улучшить:

(function(open) {
    XMLHttpRequest.prototype.open = function() {
        this.addEventListener("readystatechange", function() {
            console.log(this.readyState);
        }, false);
        open.apply(this, arguments);
    };
})(XMLHttpRequest.prototype.open);

Предпочитаете использовать аргументы apply + для вызова, потому что вам не нужно явно знать все аргументы, которые нужно открыть, которые могут измениться!

Ответ 2

Как изменить модификацию XMLHttpRequest.prototype.open или отправить методы с заменой, которые устанавливают свои собственные обратные вызовы и вызывают исходные методы? Обратный вызов может выполнить свою задачу, а затем вызвать обратный вызов указанного исходного кода.

Другими словами:

XMLHttpRequest.prototype.realOpen = XMLHttpRequest.prototype.open;

var myOpen = function(method, url, async, user, password) {
    //do whatever mucking around you want here, e.g.
    //changing the onload callback to your own version


    //call original
    this.realOpen (method, url, async, user, password);
}  


//ensure all XMLHttpRequests use our custom open method
XMLHttpRequest.prototype.open = myOpen ;

Ответ 3

Протестировано в Chrome 55 и Firefox 50.1.0

В моем случае я хотел изменить responseText, который в Firefox был свойством только для чтения, поэтому мне пришлось обернуть весь объект XMLHttpRequest. Я не реализовал весь API (в частности, responseType), но он был достаточно хорош, чтобы использовать для всех библиотек, которые у меня есть.

Использование:

    XHRProxy.addInterceptor(function(method, url, responseText, status) {
        if (url.endsWith('.html') || url.endsWith('.htm')) {
            return "<!-- HTML! -->" + responseText;
        }
    });

код:

(function(window) {

    var OriginalXHR = XMLHttpRequest;

    var XHRProxy = function() {
        this.xhr = new OriginalXHR();

        function delegate(prop) {
            Object.defineProperty(this, prop, {
                get: function() {
                    return this.xhr[prop];
                },
                set: function(value) {
                    this.xhr.timeout = value;
                }
            });
        }
        delegate.call(this, 'timeout');
        delegate.call(this, 'responseType');
        delegate.call(this, 'withCredentials');
        delegate.call(this, 'onerror');
        delegate.call(this, 'onabort');
        delegate.call(this, 'onloadstart');
        delegate.call(this, 'onloadend');
        delegate.call(this, 'onprogress');
    };
    XHRProxy.prototype.open = function(method, url, async, username, password) {
        var ctx = this;

        function applyInterceptors(src) {
            ctx.responseText = ctx.xhr.responseText;
            for (var i=0; i < XHRProxy.interceptors.length; i++) {
                var applied = XHRProxy.interceptors[i](method, url, ctx.responseText, ctx.xhr.status);
                if (applied !== undefined) {
                    ctx.responseText = applied;
                }
            }
        }
        function setProps() {
            ctx.readyState = ctx.xhr.readyState;
            ctx.responseText = ctx.xhr.responseText;
            ctx.responseURL = ctx.xhr.responseURL;
            ctx.responseXML = ctx.xhr.responseXML;
            ctx.status = ctx.xhr.status;
            ctx.statusText = ctx.xhr.statusText;
        }

        this.xhr.open(method, url, async, username, password);

        this.xhr.onload = function(evt) {
            if (ctx.onload) {
                setProps();

                if (ctx.xhr.readyState === 4) {
                     applyInterceptors();
                }
                return ctx.onload(evt);
            }
        };
        this.xhr.onreadystatechange = function (evt) {
            if (ctx.onreadystatechange) {
                setProps();

                if (ctx.xhr.readyState === 4) {
                     applyInterceptors();
                }
                return ctx.onreadystatechange(evt);
            }
        };
    };
    XHRProxy.prototype.addEventListener = function(event, fn) {
        return this.xhr.addEventListener(event, fn);
    };
    XHRProxy.prototype.send = function(data) {
        return this.xhr.send(data);
    };
    XHRProxy.prototype.abort = function() {
        return this.xhr.abort();
    };
    XHRProxy.prototype.getAllResponseHeaders = function() {
        return this.xhr.getAllResponseHeaders();
    };
    XHRProxy.prototype.getResponseHeader = function(header) {
        return this.xhr.getResponseHeader(header);
    };
    XHRProxy.prototype.setRequestHeader = function(header, value) {
        return this.xhr.setRequestHeader(header, value);
    };
    XHRProxy.prototype.overrideMimeType = function(mimetype) {
        return this.xhr.overrideMimeType(mimetype);
    };

    XHRProxy.interceptors = [];
    XHRProxy.addInterceptor = function(fn) {
        this.interceptors.push(fn);
    };

    window.XMLHttpRequest = XHRProxy;

})(window);

Ответ 4

Вы можете заменить объект unsafeWindow.XMLHttpRequest в документе оболочкой. Маленький код (не тестировался):

var oldFunction = unsafeWindow.XMLHttpRequest;
unsafeWindow.XMLHttpRequest = function() {
  alert("Hijacked! XHR was constructed.");
  var xhr = oldFunction();
  return {
    open: function(method, url, async, user, password) {
      alert("Hijacked! xhr.open().");
      return xhr.open(method, url, async, user, password);
    }
    // TODO: include other xhr methods and properties
  };
};

Но это имеет одну небольшую проблему: скрипты Greasemonkey выполняются после загрузки страницы, поэтому страница может использовать или хранить исходный объект XMLHttpRequest во время его последовательности загрузки, поэтому запросы, выполненные перед вашим script, или с реальным объектом XMLHttpRequest не будет отслеживаться вашим script. Я никак не могу обойти это ограничение.

Ответ 5

Я написал код для перехвата вызовов ajax при написании прокси-сервера. Он должен работать на большинстве браузеров.

Вот он: https://github.com/creotiv/AJAX-calls-intercepter

Ответ 6

Не уверен, что вы можете сделать это с помощью greasemonkey, но если вы создадите расширение, вы можете использовать службу наблюдателя и наблюдателя-клиента-наблюдателя.

Ответ 7

На основе предложенного решения я реализовал файл "xhr-extensions.ts", который можно использовать в решениях для машинописи. Как пользоваться:

  1. Добавьте файл с кодом в ваше решение

  2. Импортировать как это

    import { XhrSubscription, subscribToXhr } from "your-path/xhr-extensions";
    
  3. Подписаться, как это

    const subscription = subscribeToXhr(xhr => {
      if (xhr.status != 200) return;
      ... do something here.
    });
    
  4. Отписаться, когда вам больше не нужна подписка

    subscription.unsubscribe();
    

Содержимое файла 'xhr-extensions.ts'

    export class XhrSubscription {

      constructor(
        private callback: (xhr: XMLHttpRequest) => void
      ) { }

      next(xhr: XMLHttpRequest): void {
        return this.callback(xhr);
      }

      unsubscribe(): void {
        subscriptions = subscriptions.filter(s => s != this);
      }
    }

    let subscriptions: XhrSubscription[] = [];

    export function subscribeToXhr(callback: (xhr: XMLHttpRequest) => void): XhrSubscription {
      const subscription = new XhrSubscription(callback);
      subscriptions.push(subscription);
      return subscription;
    }

    (function (open) {
      XMLHttpRequest.prototype.open = function () {
        this.addEventListener("readystatechange", () => {
          subscriptions.forEach(s => s.next(this));
        }, false);
        return open.apply(this, arguments);
      };
    })(XMLHttpRequest.prototype.open);