initialize.js 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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 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)}' ` + `has been replayed`);
  68. }
  69. }
  70. catch (err) {
  71. await queue.unshiftRequest(entry);
  72. if (process.env.NODE_ENV !== 'production') {
  73. logger.log(`Request for '${getFriendlyURL(url.href)}' ` +
  74. `failed to replay, putting it back in the queue.`);
  75. }
  76. throw err;
  77. }
  78. }
  79. if (process.env.NODE_ENV !== 'production') {
  80. logger.log(`All Google Analytics request successfully replayed; ` +
  81. `the queue is now empty!`);
  82. }
  83. };
  84. };
  85. /**
  86. * Creates GET and POST routes to catch failed Measurement Protocol hits.
  87. *
  88. * @param {BackgroundSyncPlugin} bgSyncPlugin
  89. * @return {Array<Route>} The created routes.
  90. *
  91. * @private
  92. */
  93. const createCollectRoutes = (bgSyncPlugin) => {
  94. const match = ({ url }) => url.hostname === GOOGLE_ANALYTICS_HOST &&
  95. COLLECT_PATHS_REGEX.test(url.pathname);
  96. const handler = new NetworkOnly({
  97. plugins: [bgSyncPlugin],
  98. });
  99. return [new Route(match, handler, 'GET'), new Route(match, handler, 'POST')];
  100. };
  101. /**
  102. * Creates a route with a network first strategy for the analytics.js script.
  103. *
  104. * @param {string} cacheName
  105. * @return {Route} The created route.
  106. *
  107. * @private
  108. */
  109. const createAnalyticsJsRoute = (cacheName) => {
  110. const match = ({ url }) => url.hostname === GOOGLE_ANALYTICS_HOST &&
  111. url.pathname === ANALYTICS_JS_PATH;
  112. const handler = new NetworkFirst({ cacheName });
  113. return new Route(match, handler, 'GET');
  114. };
  115. /**
  116. * Creates a route with a network first strategy for the gtag.js script.
  117. *
  118. * @param {string} cacheName
  119. * @return {Route} The created route.
  120. *
  121. * @private
  122. */
  123. const createGtagJsRoute = (cacheName) => {
  124. const match = ({ url }) => url.hostname === GTM_HOST && url.pathname === GTAG_JS_PATH;
  125. const handler = new NetworkFirst({ cacheName });
  126. return new Route(match, handler, 'GET');
  127. };
  128. /**
  129. * Creates a route with a network first strategy for the gtm.js script.
  130. *
  131. * @param {string} cacheName
  132. * @return {Route} The created route.
  133. *
  134. * @private
  135. */
  136. const createGtmJsRoute = (cacheName) => {
  137. const match = ({ url }) => url.hostname === GTM_HOST && url.pathname === GTM_JS_PATH;
  138. const handler = new NetworkFirst({ cacheName });
  139. return new Route(match, handler, 'GET');
  140. };
  141. /**
  142. * @param {Object=} [options]
  143. * @param {Object} [options.cacheName] The cache name to store and retrieve
  144. * analytics.js. Defaults to the cache names provided by `workbox-core`.
  145. * @param {Object} [options.parameterOverrides]
  146. * [Measurement Protocol parameters](https://developers.google.com/analytics/devguides/collection/protocol/v1/parameters),
  147. * expressed as key/value pairs, to be added to replayed Google Analytics
  148. * requests. This can be used to, e.g., set a custom dimension indicating
  149. * that the request was replayed.
  150. * @param {Function} [options.hitFilter] A function that allows you to modify
  151. * the hit parameters prior to replaying
  152. * the hit. The function is invoked with the original hit's URLSearchParams
  153. * object as its only argument.
  154. *
  155. * @memberof workbox-google-analytics
  156. */
  157. const initialize = (options = {}) => {
  158. const cacheName = cacheNames.getGoogleAnalyticsName(options.cacheName);
  159. const bgSyncPlugin = new BackgroundSyncPlugin(QUEUE_NAME, {
  160. maxRetentionTime: MAX_RETENTION_TIME,
  161. onSync: createOnSyncCallback(options),
  162. });
  163. const routes = [
  164. createGtmJsRoute(cacheName),
  165. createAnalyticsJsRoute(cacheName),
  166. createGtagJsRoute(cacheName),
  167. ...createCollectRoutes(bgSyncPlugin),
  168. ];
  169. const router = new Router();
  170. for (const route of routes) {
  171. router.registerRoute(route);
  172. }
  173. router.addFetchListener();
  174. };
  175. export { initialize };