Last active
August 3, 2022 15:24
-
-
Save catdad/2cf9e2147bf327052e8b to your computer and use it in GitHub Desktop.
A simple example of overloading XMLHttpRequest to always send a custom header
This file contains hidden or 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
// get real XMLHttpRequest object | |
var RealXMLHttpRequest = window.XMLHttpRequest; | |
// create the overloaded XMLHttpObject | |
window.XMLHttpRequest = function(){ | |
// just in case someone is still using IE6, use a fallback | |
var ajax = !!RealXMLHttpRequest ? new RealXMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"), | |
realOpen = ajax.open; | |
// steal the 'open' function, since the request has o be open | |
// in order to send headers | |
ajax.open = function(method, url){ | |
realOpen.apply(ajax, arguments); | |
// note: here, yu have access to the method (GET, POST, etc.), as well | |
// as the url for the request... so 'if' to your content | |
// automatically send the header once open | |
ajax.setRequestHeader('X-Catdad-Custom', 'meow'); | |
}; | |
return ajax; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment