initialize.mjs 6.6 KB

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