2017-03-03 47 views
7

我想標記正在存儲在服務工作者緩存中的資源。是否可以修改服務工作者高速緩存響應頭?

我認爲可以將自定義標題添加到資源中,這可能表明這一點,但是,一旦資源存儲在服務工作者緩存中,似乎會刪除標題修改。是這樣嗎? cache spec中沒有關於修改響應頭的信息。

這裏是什麼,我都試過一個例子:

// I successfully cache a resource (confirmed in Dev Tools) 
caches.open('testCache').then(cache => { 
    cache.add('kitten.jpg'); 
}) 
.then(() => { 
    console.log('successfully cached image'); // logs as expected 
}); 

// placeholder 
var modifiedResponse; 

// get the cached resource 
caches.open('testCache') 
.then(cache => { 
    return cache.match('kitten.jpg'); 
}) 

// modify the resource's headers 
.then(response => { 
    modifiedResponse = response; 
    modifiedResponse.headers.append('x-new-header', 'test-value'); 
    // confirm that the header was modified 
    console.log(modifiedResponse.headers.get('x-new-header')); // logs 'test-value' 
    return caches.open('testCache'); 
}) 

// put the modified resource back into the cache 
.then((cache) => { 
    return cache.put('kitten.jpg', modifiedResponse); 
}) 

// get the modified resource back out again 
.then(() => { 
    return caches.match('kitten.jpg'); 
}) 

// the modifed header wasn't saved! 
.then(response => { 
    console.log(response.headers.get('x-new-header')); // logs null 
}); 

我也曾嘗試刪除自定義頁眉,修改現有的報頭,並創建new Response()響應對象,而不是抓住現有的。

編輯:我使用的是Chrome 56

+1

這將是有益的,包括測試中使用的瀏覽器的名稱和版本。 – tony19

+0

@ tony19啊對,謝謝。我正在使用Chrome 56.我更新了這個問題。 –

回答

4

你將不得不創建一個新的響應要做到這一點:

fetch('./').then(response => { 
    console.log(new Map(response.headers)); 

    const newHeaders = new Headers(response.headers); 
    newHeaders.append('x-foo', 'bar'); 

    const anotherResponse = new Response(response.body, { 
    status: response.status, 
    statusText: response.statusText, 
    headers: newHeaders 
    }); 

    console.log(new Map(anotherResponse.headers)); 
}); 

Live demo(見控制檯)

相關問題