- Help Center
- Developers
- Tips & Tricks
Detect AJAX events with JavaScript
There are times when you might want to monitor AJAX requests made from a page.
The following provides a simple way to monitor AJAX events by TYPE, request URL and response payload.
const originalXMLHttpRequest = XMLHttpRequest.prototype.open XMLHttpRequest.prototype.open = function (type, url) { // do URL matching here if needed if (url.indexOf('/some/request/url/you/want/to/listen/to') !== -1) { this.addEventListener('load', function () { // match some JSON values on responseText if (this.responseText.includes('"env_shopOnBehalfSessionEstablished" : "true"') && this.responseText.includes('"env_shopOnBehalfEnabled_CSR" : "true"')) { // Do some work } }) } originalXMLHttpRequest.apply(this, arguments) }
The following method provides more hooks into XMLHttpRequest if they are needed.
var s_ajaxListener = new Object(); s_ajaxListener.tempOpen = XMLHttpRequest.prototype.open; s_ajaxListener.tempSend = XMLHttpRequest.prototype.send; s_ajaxListener.callback = function() { console.log(this.method + ':' + this.url + '\n' + this.data); if (this.url == 'mypath') { // actions } } XMLHttpRequest.prototype.open = function(a, b) { if (!a) var a = ''; if (!b) var b = ''; s_ajaxListener.tempOpen.apply(this, arguments); s_ajaxListener.method = a; s_ajaxListener.url = b; if (a.toLowerCase() == 'get') { s_ajaxListener.data = b.split('?'); s_ajaxListener.data = s_ajaxListener.data[1]; } } XMLHttpRequest.prototype.send = function(a, b) { if (!a) var a = ''; if (!b) var b = ''; s_ajaxListener.tempSend.apply(this, arguments); if (s_ajaxListener.method.toLowerCase() == 'post') s_ajaxListener.data = a; s_ajaxListener.callback(); }
From: https://stackoverflow.com/questions/3596583/javascript-detect-an-ajax-event