Skip to content

Commit 22f7bcf

Browse files
committed
Fix fetch issues with browser extension resources
1 parent aec4633 commit 22f7bcf

File tree

1 file changed

+37
-5
lines changed

1 file changed

+37
-5
lines changed

views/service-worker.js.erb

Lines changed: 37 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,34 @@ const urlsToCache = [
1111
'<%= doc_index_urls.join "',\n '" %>',
1212
];
1313

14+
<%# Clone a request with the mode set to 'cors' %>
15+
function corsify(request) {
16+
const options = {
17+
mode: 'cors',
18+
};
19+
20+
const keys = [
21+
'body',
22+
'cache',
23+
'credentials',
24+
'headers',
25+
'integrity',
26+
'keepalive',
27+
'method',
28+
'redirect',
29+
'referrer',
30+
'referrerPolicy',
31+
'signal',
32+
'window',
33+
];
34+
35+
for (const key of keys) {
36+
options[key] = request[key];
37+
}
38+
39+
return new Request(request.url, options);
40+
}
41+
1442
<%# Set-up the cache %>
1543
self.addEventListener('install', event => {
1644
self.skipWaiting();
@@ -36,21 +64,25 @@ self.addEventListener('fetch', event => {
3664
if (cachedResponse) return cachedResponse;
3765

3866
try {
39-
const response = await fetch(event.request);
67+
const response = await fetch(corsify(event.request));
4068

41-
if (!response.ok) {
69+
<%# If the status code is 0 it means the response is opaque %>
70+
<%# If the response is opaque it's not possible to read whether it is successful or not, so we assume it is %>
71+
if (!response.ok && response.status !== 0) {
4272
throw new Error(`The HTTP request failed with status code ${response.status}`);
4373
}
4474

4575
return response;
4676
} catch (err) {
4777
const url = new URL(event.request.url);
4878

49-
<%# Attempt to return the index page from the cache if the user is visiting a url like devdocs.io/offline or devdocs.io/javascript/global_objects/array/find %>
50-
<%# The index page will make sure the correct documentation or a proper offline page is shown %>
5179
const pathname = url.pathname;
5280
const filename = pathname.substr(1 + pathname.lastIndexOf('/')).split(/\#|\?/g)[0];
53-
if (url.origin === location.origin && !['.css', '.js', '.json', '.png', '.ico', '.svg', '.xml'].some(ext => filename.endsWith(ext))) {
81+
const extensions = ['.html', '.css', '.js', '.json', '.png', '.ico', '.svg', '.xml'];
82+
83+
<%# Attempt to return the index page from the cache if the user is visiting a url like devdocs.io/offline or devdocs.io/javascript/global_objects/array/find %>
84+
<%# The index page will make sure the correct documentation or a proper offline page is shown %>
85+
if (url.origin === location.origin && !extensions.some(ext => filename.endsWith(ext))) {
5486
const cachedIndex = await caches.match('/');
5587
if (cachedIndex) return cachedIndex;
5688
}

0 commit comments

Comments
 (0)