Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

3 лет назад
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. /*
  2. Copyright 2017 Google Inc. All Rights Reserved.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. import {Plugin} from 'workbox-background-sync/Plugin.mjs';
  14. import {cacheNames} from 'workbox-core/_private/cacheNames.mjs';
  15. import {Route} from 'workbox-routing/Route.mjs';
  16. import {Router} from 'workbox-routing/Router.mjs';
  17. import {NetworkFirst} from 'workbox-strategies/NetworkFirst.mjs';
  18. import {NetworkOnly} from 'workbox-strategies/NetworkOnly.mjs';
  19. import {
  20. QUEUE_NAME,
  21. MAX_RETENTION_TIME,
  22. GOOGLE_ANALYTICS_HOST,
  23. GTM_HOST,
  24. ANALYTICS_JS_PATH,
  25. GTAG_JS_PATH,
  26. COLLECT_PATHS_REGEX,
  27. } from './utils/constants.mjs';
  28. import './_version.mjs';
  29. /**
  30. * Promisifies the FileReader API to await a text response from a Blob.
  31. *
  32. * @param {Blob} blob
  33. * @return {Promise<string>}
  34. *
  35. * @private
  36. */
  37. const getTextFromBlob = async (blob) => {
  38. // This usage of `return await new Promise...` is intentional to work around
  39. // a bug in the transpiled/minified output.
  40. // See https://github.com/GoogleChrome/workbox/issues/1186
  41. return await new Promise((resolve, reject) => {
  42. const reader = new FileReader();
  43. reader.onloadend = () => resolve(reader.result);
  44. reader.onerror = () => reject(reader.error);
  45. reader.readAsText(blob);
  46. });
  47. };
  48. /**
  49. * Creates the requestWillDequeue callback to be used with the background
  50. * sync queue plugin. The callback takes the failed request and adds the
  51. * `qt` param based on the current time, as well as applies any other
  52. * user-defined hit modifications.
  53. *
  54. * @param {Object} config See workbox.googleAnalytics.initialize.
  55. * @return {Function} The requestWillDequeu callback function.
  56. *
  57. * @private
  58. */
  59. const createRequestWillReplayCallback = (config) => {
  60. return async (storableRequest) => {
  61. let {url, requestInit, timestamp} = storableRequest;
  62. url = new URL(url);
  63. // Measurement protocol requests can set their payload parameters in either
  64. // the URL query string (for GET requests) or the POST body.
  65. let params;
  66. if (requestInit.body) {
  67. const payload = requestInit.body instanceof Blob ?
  68. await getTextFromBlob(requestInit.body) : requestInit.body;
  69. params = new URLSearchParams(payload);
  70. } else {
  71. params = url.searchParams;
  72. }
  73. // Calculate the qt param, accounting for the fact that an existing
  74. // qt param may be present and should be updated rather than replaced.
  75. const originalHitTime = timestamp - (Number(params.get('qt')) || 0);
  76. const queueTime = Date.now() - originalHitTime;
  77. // Set the qt param prior to applying the hitFilter or parameterOverrides.
  78. params.set('qt', queueTime);
  79. if (config.parameterOverrides) {
  80. for (const param of Object.keys(config.parameterOverrides)) {
  81. const value = config.parameterOverrides[param];
  82. params.set(param, value);
  83. }
  84. }
  85. if (typeof config.hitFilter === 'function') {
  86. config.hitFilter.call(null, params);
  87. }
  88. requestInit.body = params.toString();
  89. requestInit.method = 'POST';
  90. requestInit.mode = 'cors';
  91. requestInit.credentials = 'omit';
  92. requestInit.headers = {'Content-Type': 'text/plain'};
  93. // Ignore URL search params as they're now in the post body.
  94. storableRequest.url = `${url.origin}${url.pathname}`;
  95. };
  96. };
  97. /**
  98. * Creates GET and POST routes to catch failed Measurement Protocol hits.
  99. *
  100. * @param {Plugin} queuePlugin
  101. * @return {Array<Route>} The created routes.
  102. *
  103. * @private
  104. */
  105. const createCollectRoutes = (queuePlugin) => {
  106. const match = ({url}) => url.hostname === GOOGLE_ANALYTICS_HOST &&
  107. COLLECT_PATHS_REGEX.test(url.pathname);
  108. const handler = new NetworkOnly({
  109. plugins: [queuePlugin],
  110. });
  111. return [
  112. new Route(match, handler, 'GET'),
  113. new Route(match, handler, 'POST'),
  114. ];
  115. };
  116. /**
  117. * Creates a route with a network first strategy for the analytics.js script.
  118. *
  119. * @param {string} cacheName
  120. * @return {Route} The created route.
  121. *
  122. * @private
  123. */
  124. const createAnalyticsJsRoute = (cacheName) => {
  125. const match = ({url}) => url.hostname === GOOGLE_ANALYTICS_HOST &&
  126. url.pathname === ANALYTICS_JS_PATH;
  127. const handler = new NetworkFirst({cacheName});
  128. return new Route(match, handler, 'GET');
  129. };
  130. /**
  131. * Creates a route with a network first strategy for the gtag.js script.
  132. *
  133. * @param {string} cacheName
  134. * @return {Route} The created route.
  135. *
  136. * @private
  137. */
  138. const createGtagJsRoute = (cacheName) => {
  139. const match = ({url}) => url.hostname === GTM_HOST &&
  140. url.pathname === GTAG_JS_PATH;
  141. const handler = new NetworkFirst({cacheName});
  142. return new Route(match, handler, 'GET');
  143. };
  144. /**
  145. * @param {Object=} [options]
  146. * @param {Object} [options.cacheName] The cache name to store and retrieve
  147. * analytics.js. Defaults to the cache names provided by `workbox-core`.
  148. * @param {Object} [options.parameterOverrides]
  149. * [Measurement Protocol parameters](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters),
  150. * expressed as key/value pairs, to be added to replayed Google Analytics
  151. * requests. This can be used to, e.g., set a custom dimension indicating
  152. * that the request was replayed.
  153. * @param {Function} [options.hitFilter] A function that allows you to modify
  154. * the hit parameters prior to replaying
  155. * the hit. The function is invoked with the original hit's URLSearchParams
  156. * object as its only argument.
  157. *
  158. * @memberof workbox.googleAnalytics
  159. */
  160. const initialize = (options = {}) => {
  161. const cacheName = cacheNames.getGoogleAnalyticsName(options.cacheName);
  162. const queuePlugin = new Plugin(QUEUE_NAME, {
  163. maxRetentionTime: MAX_RETENTION_TIME,
  164. callbacks: {
  165. requestWillReplay: createRequestWillReplayCallback(options),
  166. },
  167. });
  168. const routes = [
  169. createAnalyticsJsRoute(cacheName),
  170. createGtagJsRoute(cacheName),
  171. ...createCollectRoutes(queuePlugin),
  172. ];
  173. const router = new Router();
  174. for (const route of routes) {
  175. router.registerRoute(route);
  176. }
  177. self.addEventListener('fetch', (evt) => {
  178. const responsePromise = router.handleRequest(evt);
  179. if (responsePromise) {
  180. evt.respondWith(responsePromise);
  181. }
  182. });
  183. };
  184. export {
  185. initialize,
  186. };