Skip to content

Commit e1e81c8

Browse files
author
evgeny-nadymov
committed
Service worker template
1 parent 8778ebc commit e1e81c8

File tree

3 files changed

+219
-7
lines changed

3 files changed

+219
-7
lines changed

‎service-worker.tmpl

+209
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,209 @@
1+
/**
2+
* Copyright 2016 Google Inc. All rights reserved.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
// DO NOT EDIT THIS GENERATED OUTPUT DIRECTLY!
18+
// This file should be overwritten as part of your build process.
19+
// If you need to extend the behavior of the generated service worker, the best approach is to write
20+
// additional code and include it using the importScripts option:
21+
// https://github.com/GoogleChrome/sw-precache#importscripts-arraystring
22+
//
23+
// Alternatively, it's possible to make changes to the underlying template file and then use that as the
24+
// new base for generating output, via the templateFilePath option:
25+
// https://github.com/GoogleChrome/sw-precache#templatefilepath-string
26+
//
27+
// If you go that route, make sure that whenever you update your sw-precache dependency, you reconcile any
28+
// changes made to this original template file with your modified copy.
29+
30+
// This generated service worker JavaScript will precache your site's resources.
31+
// The code needs to be saved in a .js file at the top-level of your site, and registered
32+
// from your pages in order to be used. See
33+
// https://github.com/googlechrome/sw-precache/blob/master/demo/app/js/service-worker-registration.js
34+
// for an example of how you can register this script and handle various service worker events.
35+
36+
/* eslint-env worker, serviceworker */
37+
/* eslint-disable indent, no-unused-vars, no-multiple-empty-lines, max-nested-callbacks, space-before-function-paren, quotes, comma-spacing */
38+
'use strict';
39+
40+
var precacheConfig = <%= precacheConfig %>;
41+
var cacheName = 'sw-precache-<%= version %>-<%= cacheId %>-' + (self.registration ? self.registration.scope : '');
42+
43+
<% if (handleFetch) { %>
44+
var ignoreUrlParametersMatching = [<%= ignoreUrlParametersMatching %>];
45+
<% } %>
46+
47+
<% Object.keys(externalFunctions).sort().forEach(function(functionName) {%>
48+
var <%- functionName %> = <%= externalFunctions[functionName] %>;
49+
<% }); %>
50+
51+
var hashParamName = '_sw-precache';
52+
var urlsToCacheKeys = new Map(
53+
precacheConfig.map(function(item) {
54+
var relativeUrl = item[0];
55+
var hash = item[1];
56+
var absoluteUrl = new URL(relativeUrl, self.location);
57+
var cacheKey = createCacheKey(absoluteUrl, hashParamName, hash, <%= dontCacheBustUrlsMatching %>);
58+
return [absoluteUrl.toString(), cacheKey];
59+
})
60+
);
61+
62+
function setOfCachedUrls(cache) {
63+
return cache.keys().then(function(requests) {
64+
return requests.map(function(request) {
65+
return request.url;
66+
});
67+
}).then(function(urls) {
68+
return new Set(urls);
69+
});
70+
}
71+
72+
self.addEventListener('install', function(event) {
73+
event.waitUntil(
74+
caches.open(cacheName).then(function(cache) {
75+
return setOfCachedUrls(cache).then(function(cachedUrls) {
76+
return Promise.all(
77+
Array.from(urlsToCacheKeys.values()).map(function(cacheKey) {
78+
// If we don't have a key matching url in the cache already, add it.
79+
if (!cachedUrls.has(cacheKey)) {
80+
var request = new Request(cacheKey, {credentials: 'same-origin'});
81+
return fetch(request).then(function(response) {
82+
// Bail out of installation unless we get back a 200 OK for
83+
// every request.
84+
if (!response.ok) {
85+
throw new Error('Request for ' + cacheKey + ' returned a ' +
86+
'response with status ' + response.status);
87+
}
88+
89+
return cleanResponse(response).then(function(responseToCache) {
90+
return cache.put(cacheKey, responseToCache);
91+
});
92+
});
93+
}
94+
})
95+
);
96+
});
97+
}).then(function() {
98+
<% if (skipWaiting) { %>
99+
// Force the SW to transition from installing -> active state
100+
return self.skipWaiting();
101+
<% } %>
102+
})
103+
);
104+
});
105+
106+
self.addEventListener('activate', function(event) {
107+
var setOfExpectedUrls = new Set(urlsToCacheKeys.values());
108+
109+
event.waitUntil(
110+
caches.open(cacheName).then(function(cache) {
111+
return cache.keys().then(function(existingRequests) {
112+
return Promise.all(
113+
existingRequests.map(function(existingRequest) {
114+
if (!setOfExpectedUrls.has(existingRequest.url)) {
115+
return cache.delete(existingRequest);
116+
}
117+
})
118+
);
119+
});
120+
}).then(function() {
121+
<% if (clientsClaim) { %>
122+
return self.clients.claim();
123+
<% } %>
124+
})
125+
);
126+
});
127+
128+
<% if (handleFetch) { %>
129+
self.addEventListener('fetch', function(event) {
130+
if (event.request.method === 'GET') {
131+
// Should we call event.respondWith() inside this fetch event handler?
132+
// This needs to be determined synchronously, which will give other fetch
133+
// handlers a chance to handle the request if need be.
134+
var shouldRespond;
135+
136+
// First, remove all the ignored parameters and hash fragment, and see if we
137+
// have that URL in our cache. If so, great! shouldRespond will be true.
138+
var url = stripIgnoredUrlParameters(event.request.url, ignoreUrlParametersMatching);
139+
shouldRespond = urlsToCacheKeys.has(url);
140+
141+
// If shouldRespond is false, check again, this time with 'index.html'
142+
// (or whatever the directoryIndex option is set to) at the end.
143+
var directoryIndex = '<%= directoryIndex %>';
144+
if (!shouldRespond && directoryIndex) {
145+
url = addDirectoryIndex(url, directoryIndex);
146+
shouldRespond = urlsToCacheKeys.has(url);
147+
}
148+
149+
// If shouldRespond is still false, check to see if this is a navigation
150+
// request, and if so, whether the URL matches navigateFallbackWhitelist.
151+
var navigateFallback = '<%= navigateFallback %>';
152+
if (!shouldRespond &&
153+
navigateFallback &&
154+
(event.request.mode === 'navigate') &&
155+
isPathWhitelisted(<%= navigateFallbackWhitelist %>, event.request.url)) {
156+
url = new URL(navigateFallback, self.location).toString();
157+
shouldRespond = urlsToCacheKeys.has(url);
158+
}
159+
160+
// If shouldRespond was set to true at any point, then call
161+
// event.respondWith(), using the appropriate cache key.
162+
console.log("[SW] fetch url " + url, shouldRespond);
163+
if (shouldRespond) {
164+
event.respondWith(
165+
caches.open(cacheName).then(function(cache) {
166+
return cache.match(urlsToCacheKeys.get(url)).then(function(response) {
167+
if (response) {
168+
let url = event.request.url;
169+
console.log("[SW] found cached url " + url);
170+
/*if (url.indexOf(".wasm") > -1) {
171+
console.log("[SW] wasm not modified");
172+
let responseInit = {
173+
status: 304,
174+
statusText: 'Not Modified'
175+
};
176+
let notModifiedResponse = new Response('', responseInit);
177+
return notModifiedResponse;
178+
}*/
179+
180+
return response;
181+
}
182+
throw Error('The cached response that was expected is missing.');
183+
});
184+
}).catch(function(e) {
185+
// Fall back to just fetch()ing the request if some unexpected error
186+
// prevented the cached response from being valid.
187+
console.warn('Couldn\'t serve response for "%s" from cache: %O', event.request.url, e);
188+
return fetch(event.request);
189+
})
190+
);
191+
}
192+
}
193+
});
194+
195+
<% if (swToolboxCode) { %>
196+
// *** Start of auto-included sw-toolbox code. ***
197+
<%= swToolboxCode %>
198+
// *** End of auto-included sw-toolbox code. ***
199+
<% } %>
200+
201+
<% if (runtimeCaching) { %>
202+
// Runtime cache configuration, using the sw-toolbox library.
203+
<%= runtimeCaching %>
204+
<% } %>
205+
<% } %>
206+
207+
<% if (importScripts) { %>
208+
importScripts(<%= importScripts %>);
209+
<% } %>

‎src/registerServiceWorker.js

+9-7
Original file line numberDiff line numberDiff line change
@@ -21,13 +21,15 @@ import TdLibController from './Controllers/TdLibController';
2121
// To learn more about the benefits of this model, read https://goo.gl/KwvDNy.
2222
// This link also includes instructions on opting out of this behavior.
2323

24-
const isLocalhost = Boolean(
25-
window.location.hostname === 'localhost' ||
26-
// [::1] is the IPv6 localhost address.
27-
window.location.hostname === '[::1]' ||
28-
// 127.0.0.1/8 is considered localhost for IPv4.
29-
window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)
30-
);
24+
const isLocalhost =
25+
//false;
26+
Boolean(
27+
window.location.hostname === 'localhost' ||
28+
// [::1] is the IPv6 localhost address.
29+
window.location.hostname === '[::1]' ||
30+
// 127.0.0.1/8 is considered localhost for IPv4.
31+
window.location.hostname.match(/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/)
32+
);
3133

3234
export default async function register() {
3335
console.log('[SW] Register');

‎sw-config.js

+1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ module.exports = {
1717
stripPrefix: './build',
1818
replacePrefix: '/telegram-react',
1919
maximumFileSizeToCacheInBytes: 10485760,
20+
templateFilePath: './service-worker.tmpl',
2021
importScripts: ['./custom-service-worker.js'],
2122
ignoreUrlParametersMatching: [/./]
2223
};

0 commit comments

Comments
 (0)