Нет собственного способа перехватить вызовы на window.fetch
.Вы можете создать минимальный класс-обертку, который будет выполнять этот вызов для вас и позволять вам передавать ему before-send ловушки, которые он выполнит заранее:
//-----------------------------------------------------------
// Implementation:
//-----------------------------------------------------------
class CustomFetch {
constructor(url, init = {}) {
this.url = url;
this.init = init;
this.promise = null;
this.beforeSends = [];
}
/**
* Runs the actual fetch call.
* @return {Promise<Response>}
*/
fetch() {
this._runBeforeSends();
this.promise = fetch(this.url, this.init);
return this.promise;
}
/**
* Runs all registered before-send functions
*/
_runBeforeSends() {
this.beforeSends.forEach(fn => fn(this));
return this;
}
/**
* Register a beforesend handler.
* @param {function(url, init): void} fn
*/
beforeSend(fn) {
this.beforeSends.push(fn);
return this;
}
}
//-----------------------------------------------------------
// Usage example:
//-----------------------------------------------------------
// Create a special fetch wrapper with pre-defined arguments for 'Actual fetch':
const postFetch = new CustomFetch('https://jsonplaceholder.typicode.com/posts/1');
// Register a before-send handler:
postFetch.beforeSend((fetch) => {
console.log(`About to send to ${fetch.url}`);
});
// call the fetch() method and get back the Promise<Response>
// of the native fetch call:
const posP = postFetch.fetch();
// When loaded, log the response data
posP.then((res) => res.json()).then(console.log);
Это немного более многословно, чем простая функция-обертка, но также дает вам возможность повторно использовать экземпляр CustomFetch
- вы можете продолжать вызыватьsomeFetch.fetch()
, и он, в свою очередь, продолжит вызывать зарегистрированные обработчики перед отправкой, прежде чем продолжить window.fetch
.