[英]Fetch() request immediately failing in service worker running through Android Webview
我有一個服務工作者,我用它來啟用我網站的離線版本。 這很好用。 我還有一個 Android 應用程序,它基本上只是加載我的網站的 web 視圖的包裝器。
一切都很好,直到大約 2-3 周前 Fetch() 請求立即開始失敗。 只有在通過 Android webview 運行時才會失敗。 通過瀏覽器運行工作正常。 如果資源已經緩存(即通過安裝事件),那么它工作得很好,只有當我得到一個沒有緩存的頁面時。
我的服務工作者中的代碼:
self.addEventListener("fetch", function (event) {
if (event.request.method !== 'GET'
|| event.request.url.toLowerCase().indexOf('//ws') > -1
|| event.request.url.toLowerCase().indexOf('localws') > -1) {
// Don't intercept requests made to the web service
// If we don't block the event as shown below, then the request will go to
// the network as usual.
return;
}
event.respondWith(async function () {
// override the default behavior
var oCache = await caches.open('cp_' + version);
var cached = await oCache.match(event.request.url);
if (cached && cached.status < 300) {
return cached;
}
// Need to make a call to the network
try {
var oResp = await fetch(event.request); // THIS LINE CAUSES THE PROBLEM!!!
return oResp;
} catch (oError) {
console.log('SW WORKER: fetch request to network failed.', event.request);
return new Response('<h1>Offline_sw.js: An error has occured. Please try again.</h1><br><h2>Could not load URL: ' + event.request.url + '</h2>', {
status: 503,
statusText: 'Service Unavailable',
headers: new Headers({
'Content-Type': 'text/html'
})
});
}
}()); // event.respondwith
}); // fetch
線路:
var oResp = await fetch(event.request);
一旦我確定它沒有被緩存並且似乎是罪魁禍首,就會被調用。 當它出錯時,我在 catch() 中收到以下錯誤:“無法獲取”
這看起來很一般,沒有幫助。 同樣,這在通過瀏覽器時有效,所以我知道這不是 CORS 問題,不是服務人員在錯誤的目錄中等。同樣,它一直工作到大約 3 周前,現在我從客戶那里收到報告說它不起作用.
這是我發送的實際 event.request 的屏幕截圖:
在 chrome 開發人員工具(用於調試 webview)中,我看到以下內容:
我做錯了什么還是這是最近發布的 webview/chrome 中的錯誤? (我這么說是因為 chrome 為 webview 提供了動力)
看起來這是鉻的錯誤。 請參閱 bugs.chromium.org/p/chromium/issues/detail?id=977784。 應該在 v 76 中修復。
作為解決方法(如鏈接所述),您可以將以下內容添加到您的 android 代碼中:
ServiceWorkerController oSWController = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N){
oSWController = ServiceWorkerController.getInstance();
oSWController.setServiceWorkerClient(new ServiceWorkerClient(){
@Nullable
@Override
public WebResourceResponse shouldInterceptRequest(WebResourceRequest request){
return super.shouldInterceptRequest(request);
}
});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.