I want to call a function during sending a request and after receiving response with every fetch() function using Vanilla JS. I saw that jquery ajax is providing some kind of $.ajaxsetup for doing this but I want to do it with Vanilla JS. Thanks in advance.
fetch doesn't have a feature like that. You could write a wrapper function though:
const myFetch = async (...args) => {
do_before();
const result = await fetch(...args);
do_after();
return result;
}
and then call that function instead of accessing fetch directly.
You can do it by overriding the fetch function
// First rename original fetch function
window.originalFetch = window.fetch
// Then override fetch function with your new function
window.fetch = async (... args) => {
console.log("before");
// call the renamed fetch function
const result = await window.originalFetch(...args);
console.log("after");
return result;
}
// Then you can use it
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => console.log(data));
Explanation:
First, you change the original function name, then you write your own function with the same name "fetch"
Thanks to @Quentin some of the code copied from his answer