// 拦截请求
const XHR = window.XMLHttpRequest
window.XMLHttpRequest = class XMLHttpRequest extends XHR {
method = 'GET'
constructor() {
super()
const { open } = this
this.open = (
method: string,
url: string | URL,
async?: boolean,
username?: string | null,
password?: string | null,
) => {
this.method = method || 'GET'
window.dispatchEvent(
new CustomEvent('ajax_interceptor_start', {
detail: {
methods: this.method,
url,
},
}),
)
open.apply(this, [method, url, async !== undefined ? async : true, username, password])
}
this.addEventListener(
'readystatechange',
() => {
if (this.readyState === 4) {
window.dispatchEvent(
new CustomEvent('ajax_interceptor', {
detail: {
method: this.method,
status: this.status,
url: this.responseURL,
response: this.response,
},
}),
)
}
},
false,
)
}
}
if (window.fetch) {
const Fetch = window.fetch
window.fetch = (url, init) => {
window.dispatchEvent(
new CustomEvent('ajax_interceptor_start', {
detail: {
methods: init?.method || 'GET',
url,
},
}),
)
return Fetch(url, init).then(async response => {
const data = await response.clone().text()
window.dispatchEvent(
new CustomEvent('ajax_interceptor', {
detail: {
methods: init?.method || 'GET',
status: response.status,
url: response.url,
response: data,
},
}),
)
return response
})
}
}
请求拦截 XMLHttpRequest和fetch
最新推荐文章于 2023-11-17 11:15:11 发布