I would like to override window.fetch in order to add some custom headers to all ajax requests, something similar to the way xhr can be overridden.
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;
I want to be able to to do this inside a webview on android. I have tried add custom headers using shouldInterceptUrl (e.g. https://artemzin.com/blog/use-okhttp-to-load-resources-for-webview/ ) but it is something that is not recommended.
Somewhere on the page we need to register a 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: I haven't tested it it's a quite a task to set it up and have a service worker whitelisted and be able to register it, not even sure this is 100% correct but close at least
Also not sure if it works in android webview
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With