Skip to content

Instantly share code, notes, and snippets.

@catdad
Last active August 3, 2022 15:24
Show Gist options
  • Save catdad/2cf9e2147bf327052e8b to your computer and use it in GitHub Desktop.
Save catdad/2cf9e2147bf327052e8b to your computer and use it in GitHub Desktop.
A simple example of overloading XMLHttpRequest to always send a custom header
// 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