Capture All Fetch Api AJAX Requests

How would you connect all AJAX requests that use Fetch Api? Previously, we could do something similar to bind all XMLHttpRequest:

(function() { var origOpen = XMLHttpRequest.prototype.open; XMLHttpRequest.prototype.open = function() { console.log('request started!'); this.addEventListener('load', function() { console.log('request completed!'); console.log(this.readyState); //will always be 4 (ajax is completed successfully) console.log(this.responseText); //whatever the response was }); origOpen.apply(this, arguments); }; })(); 

Or even better, if you want to add to the above function, how would you connect all Fetch Api and all XMLHttpRequest AJAX requests?

+4
javascript ajax fetch-api
Jun 23 '17 at 19:31 on
source share
1 answer

In fact, Fetch Api is supported by its own browser and has only one interface: fetch . The constructor returns one Promise , and you cannot receive Request , Response when you want to return your promise to rewrite the selection constructor.

The following code does not work.

 (function() { var oldFectch = fetch; fetch.consotructor = function() { return new Promise(resolve, reject) { // your hook code }; }; })(); 

So, does this mean that we cannot hook all the Fetch Api? NO!

Firstly, thanks window.fetch polyfill .

Then do something (edit fetch.js ) and rock.

 (function(self) { 'use strict'; // comment or delete the following code block // if (self.fetch) { // return // } var support = { searchParams: 'URLSearchParams' in self, iterable: 'Symbol' in self && 'iterator' in Symbol, // ... 

Finally, fix everything that is better for you!

 self.fetch = function(input, init) { return new Promise(function(resolve, reject) { var request = new Request(input, init) var xhr = new XMLHttpRequest() // Here we go! // Now we get the XMLHttpRequest Object // Do what you want! xhr.onload = function() { var options = { status: xhr.status, statusText: xhr.statusText, headers: parseHeaders(xhr.getAllResponseHeaders() || '') } options.url = 'responseURL' in xhr ? xhr.responseURL : options.headers.get('X-Request-URL') var body = 'response' in xhr ? xhr.response : xhr.responseText resolve(new Response(body, options)) } // ... 
0
Nov 16 '17 at 10:13
source share



All Articles