BroadcastCacheUpdate.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151
  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 { assert } from 'workbox-core/_private/assert.js';
  8. import { timeout } from 'workbox-core/_private/timeout.js';
  9. import { resultingClientExists } from 'workbox-core/_private/resultingClientExists.js';
  10. import { logger } from 'workbox-core/_private/logger.js';
  11. import { responsesAreSame } from './responsesAreSame.js';
  12. import { CACHE_UPDATED_MESSAGE_TYPE, CACHE_UPDATED_MESSAGE_META, DEFAULT_HEADERS_TO_CHECK } from './utils/constants.js';
  13. import './_version.js';
  14. // UA-sniff Safari: https://stackoverflow.com/questions/7944460/detect-safari-browser
  15. // TODO(philipwalton): remove once this Safari bug fix has been released.
  16. // https://bugs.webkit.org/show_bug.cgi?id=201169
  17. const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  18. /**
  19. * Generates the default payload used in update messages. By default the
  20. * payload includes the `cacheName` and `updatedURL` fields.
  21. *
  22. * @return Object
  23. * @private
  24. */
  25. function defaultPayloadGenerator(data) {
  26. return {
  27. cacheName: data.cacheName,
  28. updatedURL: data.request.url,
  29. };
  30. }
  31. /**
  32. * Uses the `postMessage()` API to inform any open windows/tabs when a cached
  33. * response has been updated.
  34. *
  35. * For efficiency's sake, the underlying response bodies are not compared;
  36. * only specific response headers are checked.
  37. *
  38. * @memberof module:workbox-broadcast-update
  39. */
  40. class BroadcastCacheUpdate {
  41. /**
  42. * Construct a BroadcastCacheUpdate instance with a specific `channelName` to
  43. * broadcast messages on
  44. *
  45. * @param {Object} options
  46. * @param {Array<string>} [options.headersToCheck=['content-length', 'etag', 'last-modified']]
  47. * A list of headers that will be used to determine whether the responses
  48. * differ.
  49. * @param {string} [options.generatePayload] A function whose return value
  50. * will be used as the `payload` field in any cache update messages sent
  51. * to the window clients.
  52. */
  53. constructor({ headersToCheck, generatePayload, } = {}) {
  54. this._headersToCheck = headersToCheck || DEFAULT_HEADERS_TO_CHECK;
  55. this._generatePayload = generatePayload || defaultPayloadGenerator;
  56. }
  57. /**
  58. * Compares two [Responses](https://developer.mozilla.org/en-US/docs/Web/API/Response)
  59. * and sends a message (via `postMessage()`) to all window clients if the
  60. * responses differ (note: neither of the Responses can be
  61. * {@link http://stackoverflow.com/questions/39109789|opaque}).
  62. *
  63. * The message that's posted has the following format (where `payload` can
  64. * be customized via the `generatePayload` option the instance is created
  65. * with):
  66. *
  67. * ```
  68. * {
  69. * type: 'CACHE_UPDATED',
  70. * meta: 'workbox-broadcast-update',
  71. * payload: {
  72. * cacheName: 'the-cache-name',
  73. * updatedURL: 'https://example.com/'
  74. * }
  75. * }
  76. * ```
  77. *
  78. * @param {Object} options
  79. * @param {Response} [options.oldResponse] Cached response to compare.
  80. * @param {Response} options.newResponse Possibly updated response to compare.
  81. * @param {Request} options.request The request.
  82. * @param {string} options.cacheName Name of the cache the responses belong
  83. * to. This is included in the broadcast message.
  84. * @param {Event} [options.event] event An optional event that triggered
  85. * this possible cache update.
  86. * @return {Promise} Resolves once the update is sent.
  87. */
  88. async notifyIfUpdated(options) {
  89. if (process.env.NODE_ENV !== 'production') {
  90. assert.isType(options.cacheName, 'string', {
  91. moduleName: 'workbox-broadcast-update',
  92. className: 'BroadcastCacheUpdate',
  93. funcName: 'notifyIfUpdated',
  94. paramName: 'cacheName',
  95. });
  96. assert.isInstance(options.newResponse, Response, {
  97. moduleName: 'workbox-broadcast-update',
  98. className: 'BroadcastCacheUpdate',
  99. funcName: 'notifyIfUpdated',
  100. paramName: 'newResponse',
  101. });
  102. assert.isInstance(options.request, Request, {
  103. moduleName: 'workbox-broadcast-update',
  104. className: 'BroadcastCacheUpdate',
  105. funcName: 'notifyIfUpdated',
  106. paramName: 'request',
  107. });
  108. }
  109. // Without two responses there is nothing to compare.
  110. if (!options.oldResponse) {
  111. return;
  112. }
  113. if (!responsesAreSame(options.oldResponse, options.newResponse, this._headersToCheck)) {
  114. if (process.env.NODE_ENV !== 'production') {
  115. logger.log(`Newer response found (and cached) for:`, options.request.url);
  116. }
  117. const messageData = {
  118. type: CACHE_UPDATED_MESSAGE_TYPE,
  119. meta: CACHE_UPDATED_MESSAGE_META,
  120. payload: this._generatePayload(options),
  121. };
  122. // For navigation requests, wait until the new window client exists
  123. // before sending the message
  124. if (options.request.mode === 'navigate') {
  125. let resultingClientId;
  126. if (options.event instanceof FetchEvent) {
  127. resultingClientId = options.event.resultingClientId;
  128. }
  129. const resultingWin = await resultingClientExists(resultingClientId);
  130. // Safari does not currently implement postMessage buffering and
  131. // there's no good way to feature detect that, so to increase the
  132. // chances of the message being delivered in Safari, we add a timeout.
  133. // We also do this if `resultingClientExists()` didn't return a client,
  134. // which means it timed out, so it's worth waiting a bit longer.
  135. if (!resultingWin || isSafari) {
  136. // 3500 is chosen because (according to CrUX data) 80% of mobile
  137. // websites hit the DOMContentLoaded event in less than 3.5 seconds.
  138. // And presumably sites implementing service worker are on the
  139. // higher end of the performance spectrum.
  140. await timeout(3500);
  141. }
  142. }
  143. const windows = await self.clients.matchAll({ type: 'window' });
  144. for (const win of windows) {
  145. win.postMessage(messageData);
  146. }
  147. }
  148. }
  149. }
  150. export { BroadcastCacheUpdate };