Last active
December 22, 2021 02:08
-
-
Save munro/8dec0e06304c8f93bc4494e38ba83ba5 to your computer and use it in GitHub Desktop.
Selenium Intercept HTTP Requests with JavaScript (Intercepting with a HTTP/HTTPS proxy + custom CA Cert is wayyy too much work!)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// also checkout selenium wire https://pypi.org/project/selenium-wire/ | |
function interceptHttp(onComplete) { | |
// this will get rid of any previous interceptors, feel free to change | |
// this if you want to layer them. | |
window._old_send_ = window._old_send_ || window.XMLHttpRequest.prototype.send; | |
window._old_open_ = window._old_open_ || window.XMLHttpRequest.prototype.open; | |
window._old_setRequestHeader_ = window._old_setRequestHeader_ || window.XMLHttpRequest.prototype.setRequestHeader; | |
window.XMLHttpRequest.prototype.open = function () { | |
this._openArgs = [...arguments]; | |
return window._old_open_.apply(this, arguments); | |
}; | |
window.XMLHttpRequest.prototype.setRequestHeader = function () { | |
this._requestHeaders = this._requestHeaders || {}; | |
this._requestHeaders[arguments[0]] = arguments[1]; | |
return window._old_setRequestHeader_.apply(this, arguments); | |
}; | |
window.XMLHttpRequest.prototype.send = function () { | |
console.log("SEND", this, [...arguments]); | |
this.addEventListener("load", function () { | |
onComplete({ | |
request: { | |
method: this._openArgs[0], | |
url: this._openArgs[1], | |
async: this._openArgs[2], | |
user: this._openArgs[3], | |
password: this._openArgs[4], | |
headers: this._requestHeaders || {}, | |
}, | |
response: this, | |
}); | |
}); | |
return window._old_send_.apply(this, arguments); | |
}; | |
} | |
interceptHttp((response) => { | |
const { method, url } = response.request; | |
console.log("YAY", method, url); | |
window.lastRequest = response; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment