initialize.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. /*
  2. Copyright 2018 Google LLC
  3. Use of this source code is governed by an MIT-style
  4. license that can be found in the LICENSE file or at
  5. https://opensource.org/licenses/MIT.
  6. */
  7. import { BackgroundSyncPlugin } from 'workbox-background-sync/BackgroundSyncPlugin.js';
  8. import { cacheNames } from 'workbox-core/_private/cacheNames.js';
  9. import { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';
  10. import { logger } from 'workbox-core/_private/logger.js';
  11. import { Route } from 'workbox-routing/Route.js';
  12. import { Router } from 'workbox-routing/Router.js';
  13. import { NetworkFirst } from 'workbox-strategies/NetworkFirst.js';
  14. import { NetworkOnly } from 'workbox-strategies/NetworkOnly.js';
  15. import { QUEUE_NAME, MAX_RETENTION_TIME, GOOGLE_ANALYTICS_HOST, GTM_HOST, ANALYTICS_JS_PATH, GTAG_JS_PATH, GTM_JS_PATH, COLLECT_PATHS_REGEX, } from './utils/constants.js';
  16. import './_version.js';
  17. /**
  18. * Creates the requestWillDequeue callback to be used with the background
  19. * sync plugin. The callback takes the failed request and adds the
  20. * `qt` param based on the current time, as well as applies any other
  21. * user-defined hit modifications.
  22. *
  23. * @param {Object} config See {@link module:workbox-google-analytics.initialize}.
  24. * @return {Function} The requestWillDequeue callback function.
  25. *
  26. * @private
  27. */
  28. const createOnSyncCallback = (config) => {
  29. return async ({ queue }) => {
  30. let entry;
  31. while (entry = await queue.shiftRequest()) {
  32. const { request, timestamp } = entry;
  33. const url = new URL(request.url);
  34. try {
  35. // Measurement protocol requests can set their payload parameters in
  36. // either the URL query string (for GET requests) or the POST body.
  37. const params = request.method === 'POST' ?
  38. new URLSearchParams(await request.clone().text()) :
  39. url.searchParams;
  40. // Calculate the qt param, accounting for the fact that an existing
  41. // qt param may be present and should be updated rather than replaced.
  42. const originalHitTime = timestamp - (Number(params.get('qt')) || 0);
  43. const queueTime = Date.now() - originalHitTime;
  44. // Set the qt param prior to applying hitFilter or parameterOverrides.
  45. params.set('qt', String(queueTime));
  46. // Apply `parameterOverrides`, if set.
  47. if (config.parameterOverrides) {
  48. for (const param of Object.keys(config.parameterOverrides)) {
  49. const value = config.parameterOverrides[param];
  50. params.set(param, value);
  51. }
  52. }
  53. // Apply `hitFilter`, if set.
  54. if (typeof config.hitFilter === 'function') {
  55. config.hitFilter.call(null, params);
  56. }
  57. // Retry the fetch. Ignore URL search params from the URL as they're
  58. // now in the post body.
  59. await fetch(new Request(url.origin + url.pathname, {
  60. body: params.toString(),
  61. method: 'POST',
  62. mode: 'cors',
  63. credentials: 'omit',
  64. headers: { 'Content-Type': 'text/plain' },
  65. }));
  66. if (process.env.NODE_ENV !== 'production') {
  67. logger.log(`Request for '${getFriendlyURL(url.href)}'` +
  68. `has been replayed`);
  69. }
  70. }
  71. catch (err) {
  72. await queue.unshiftRequest(entry);
  73. if (process.env.NODE_ENV !== 'production') {
  74. logger.log(`Request for '${getFriendlyURL(url.href)}'` +
  75. `failed to replay, putting it back in the queue.`);
  76. }
  77. throw err;
  78. }
  79. }
  80. if (process.env.NODE_ENV !== 'production') {
  81. logger.log(`All Google Analytics request successfully replayed; ` +
  82. `the queue is now empty!`);
  83. }
  84. };
  85. };
  86. /**
  87. * Creates GET and POST routes to catch failed Measurement Protocol hits.
  88. *
  89. * @param {BackgroundSyncPlugin} bgSyncPlugin
  90. * @return {Array<Route>} The created routes.
  91. *
  92. * @private
  93. */
  94. const createCollectRoutes = (bgSyncPlugin) => {
  95. const match = ({ url }) => url.hostname === GOOGLE_ANALYTICS_HOST &&
  96. COLLECT_PATHS_REGEX.test(url.pathname);
  97. const handler = new NetworkOnly({
  98. plugins: [bgSyncPlugin],
  99. });
  100. return [
  101. new Route(match, handler, 'GET'),
  102. new Route(match, handler, 'POST'),
  103. ];
  104. };
  105. /**
  106. * Creates a route with a network first strategy for the analytics.js script.
  107. *
  108. * @param {string} cacheName
  109. * @return {Route} The created route.
  110. *
  111. * @private
  112. */
  113. const createAnalyticsJsRoute = (cacheName) => {
  114. const match = ({ url }) => url.hostname === GOOGLE_ANALYTICS_HOST &&
  115. url.pathname === ANALYTICS_JS_PATH;
  116. const handler = new NetworkFirst({ cacheName });
  117. return new Route(match, handler, 'GET');
  118. };
  119. /**
  120. * Creates a route with a network first strategy for the gtag.js script.
  121. *
  122. * @param {string} cacheName
  123. * @return {Route} The created route.
  124. *
  125. * @private
  126. */
  127. const createGtagJsRoute = (cacheName) => {
  128. const match = ({ url }) => url.hostname === GTM_HOST &&
  129. url.pathname === GTAG_JS_PATH;
  130. const handler = new NetworkFirst({ cacheName });
  131. return new Route(match, handler, 'GET');
  132. };
  133. /**
  134. * Creates a route with a network first strategy for the gtm.js script.
  135. *
  136. * @param {string} cacheName
  137. * @return {Route} The created route.
  138. *
  139. * @private
  140. */
  141. const createGtmJsRoute = (cacheName) => {
  142. const match = ({ url }) => url.hostname === GTM_HOST &&
  143. url.pathname === GTM_JS_PATH;
  144. const handler = new NetworkFirst({ cacheName });
  145. return new Route(match, handler, 'GET');
  146. };
  147. /**
  148. * @param {Object=} [options]
  149. * @param {Object} [options.cacheName] The cache name to store and retrieve
  150. * analytics.js. Defaults to the cache names provided by `workbox-core`.
  151. * @param {Object} [options.parameterOverrides]
  152. * [Measurement Protocol parameters](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters),
  153. * expressed as key/value pairs, to be added to replayed Google Analytics
  154. * requests. This can be used to, e.g., set a custom dimension indicating
  155. * that the request was replayed.
  156. * @param {Function} [options.hitFilter] A function that allows you to modify
  157. * the hit parameters prior to replaying
  158. * the hit. The function is invoked with the original hit's URLSearchParams
  159. * object as its only argument.
  160. *
  161. * @memberof module:workbox-google-analytics
  162. */
  163. const initialize = (options = {}) => {
  164. const cacheName = cacheNames.getGoogleAnalyticsName(options.cacheName);
  165. const bgSyncPlugin = new BackgroundSyncPlugin(QUEUE_NAME, {
  166. maxRetentionTime: MAX_RETENTION_TIME,
  167. onSync: createOnSyncCallback(options),
  168. });
  169. const routes = [
  170. createGtmJsRoute(cacheName),
  171. createAnalyticsJsRoute(cacheName),
  172. createGtagJsRoute(cacheName),
  173. ...createCollectRoutes(bgSyncPlugin),
  174. ];
  175. const router = new Router();
  176. for (const route of routes) {
  177. router.registerRoute(route);
  178. }
  179. router.addFetchListener();
  180. };
  181. export { initialize, };