【问题标题】:Overriding window.fetch prototype it add custom header覆盖 window.fetch 原型它添加自定义标题
【发布时间】:2016-10-17 21:25:50
【问题描述】:

我想覆盖 window.fetch 以便为所有 ajax 请求添加一些自定义标头,类似于可以覆盖 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/ ),但不建议这样做。

【问题讨论】:

  • 不要覆盖它,拦截它并使用服务工作者编辑标题并使用fetchEvent
  • 你能给我一个例子吗?我主要使用原生 java for android ..我不太擅长 javascript :( .
  • 好了,还有更简单的方法可以做到这一点,就像fetch-cookie 为服务器端所做的那样

标签: javascript android webview xmlhttprequest fetch


【解决方案1】:

在页面某处我们需要注册一个 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:我还没有测试过,设置它并让服务人员列入白名单并能够注册它是一项艰巨的任务,甚至不确定这是 100% 正确但接近至少

也不确定它是否适用于android webview

【讨论】:

  • 谢谢,但他对我不起作用。但是在后端进行了一些更改后,我能够覆盖 XMLHttpRequest。
猜你喜欢
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
  • 1970-01-01
  • 2019-01-31
  • 2012-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多