我想覆盖 window.fetch 以便向所有 ajax 请求添加一些自定义 header ,这类似于可以覆盖 xhr 的方式。
XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send;
var newSend = function(vData) {
this.setRequestHeader('ClientId', 'ANDROID');
this.setRequestHeader('CustId', '%s');
this.realSend(vData);
};
XMLHttpRequest.prototype.send = newSend;
我希望能够在 android 上的 webview 中执行此操作。我尝试使用 shouldInterceptUrl(例如 https://artemzin.com/blog/use-okhttp-to-load-resources-for-webview/)添加自定义 header ,但不推荐这样做。
最佳答案
我们需要在页面的某处注册一个 service worker
<script>
navigator.serviceWorker.register('sw.js')
</script>
sw.js
// sw.js
function isWhatYouWant(request){
// check request if we should add headers
return true
}
self.addEventListener('fetch', event => {
if( isWhatYouWant(event.request) ){
event.request.headers.set('ClientId', 'ANDROID');
event.request.headers.set('CustId', '%s');
event.respondWith(fetch(event.request));
}
}
PS:我还没有测试过它,设置它并让 service worker 列入白名单并能够注册它是一项艰巨的任务,甚至不确定这是 100% 正确但接近至少
也不确定它是否适用于android webview
关于javascript - 覆盖 window.fetch 原型(prototype),它添加自定义 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37857871/