2017-09-03 87 views
0

我用針線2.0.0服務工作者,以及一些網頁,我現在用的是workboxSW.strategies.staleWhileRevalidate()的緩存策略:後處理網頁內容與staleWhileRevalidate

const customFilter = { 

cachedResponseWillBeUsed: function (input) { 
    try { 
     console.log('cacheResponseWillBeUsed for : ' + input.request.url); 
     // modify the response body here 
    } catch (e) { 
     console.error(e); 
    } 

    return input.cachedResponse; 
}, 

requestWillFetch: function (input) { 
    try { 
     console.log('requestWillFetch for ' + input.request.url); 
    } catch (e) { 
     console.error(e); 
    } 

    return input.request; 
}, 

fetchDidFail: function (input) { 
    console.log('A fetch request for ' + input.request.url + ' failed.'); 
} 
} 

const cachingStrategy = workboxSW.strategies.staleWhileRevalidate({ 
    plugins: [ 
     customFilter 
    ] 
}); 

workboxSW.router.registerRoute(
    new RegExp('\/(.*)/suffix/?$'), 
    cachingStrategy 
); 

也進展順利,並我可以更新從緩存獲取的響應式響應。但我想要動態修改所有響應,包括第一次從網絡獲得響應(我必須在其中插入一些JavaScript)。

從我的測試中,cachedResponseWillBeUsed只允許從緩存(按照方法名稱)後處理響應,但我還沒有找到一種方法來獲得對網絡響應的訪問(但仍然正常地使用staleWhileRevalidate策略)。

有什麼建議嗎?

非常感謝

回答

0

你在正確的沒有對應於網絡請求被成功返回RequestWrapper生命週期事件。 (如果你想看到它加了進來,作爲fetchDidSucceed或類似的東西,隨意打開一個feature request!)

您可以解決此通過編寫一個名爲strategies.staleWhileRevalidate自己的自定義處理程序,然後做了一件與回覆之前的回覆如下:

const staleWhileRevalidate = workboxSW.strategies.staleWhileRevalidate({ 
    plugins: [...], 
}); 

const cachingStrategy = async (params) => { 
    const response = await staleWhileRevalidate(params); 
    // Do something to response, like get its body, modify it, 
    // and create a new response with the updated body. 
    const modifiedResponse = modify(response); 
    return modifiedResponse; 
}; 

workboxSW.router.registerRoute(
    new RegExp('\/(.*)/suffix/?$'), 
    cachingStrategy 
); 
+0

這正是我最終做的(儘管花了一點時間才弄清楚)。 – Weeblr

+0

對不起,快速輸入。事實證明,使用cachedResponseWillBeUsed來修改響應並不是一個好主意。如果這樣做,則不能再使用WorkBox的cacheExpiration選項,因爲只能註冊一個cachedResponseWillBeUsed方法。如此專門的方法來過濾響應確實是一個好主意。 – Weeblr