Question

I want to change open() method in XMLHttpRequest objects. actually I need to change every url that will send trough xhr. how can I do this?

for example when xhr objects open one request for http://domain.com/ I want to change it to https://domain.com/

Was it helpful?

Solution

You can intrupt any method on native DOM objects but that is not recommnended. Don't do this.

Anyway if you want to know how to manipulate XMLXttpRequest's open method, this is how you do it:

var open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(){ 
   // do stuff you want 
   // for example console.log:
   console.log('test');
   // then let open method happen
   open.apply(this, arguments);
}

For your very use case that is changing protocol of URL, you can do this:

var open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function(){ 
   var link = document.createElement('a'); // make an anchar element
   link.href = arguments[1]; // make it's href equal to second argument which is URL
   link.protocol = 'https:'; // force https to the link
   arguments[1] = link.href; // write back URL form link that is now start with 'https'
   // then let open method happen
   open.apply(this, arguments);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top