BroadcastCacheUpdate.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  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_META, CACHE_UPDATED_MESSAGE_TYPE, DEFAULT_HEADERS_TO_CHECK, NOTIFY_ALL_CLIENTS, } 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 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. * @param {boolean} [options.notifyAllClients=true] If true (the default) then
  53. * all open clients will receive a message. If false, then only the client
  54. * that make the original request will be notified of the update.
  55. */
  56. constructor({ generatePayload, headersToCheck, notifyAllClients, } = {}) {
  57. this._headersToCheck = headersToCheck || DEFAULT_HEADERS_TO_CHECK;
  58. this._generatePayload = generatePayload || defaultPayloadGenerator;
  59. this._notifyAllClients = notifyAllClients !== null && notifyAllClients !== void 0 ? notifyAllClients : NOTIFY_ALL_CLIENTS;
  60. }
  61. /**
  62. * Compares two [Responses](https://developer.mozilla.org/en-US/docs/Web/API/Response)
  63. * and sends a message (via `postMessage()`) to all window clients if the
  64. * responses differ. Neither of the Responses can be
  65. * [opaque](https://developer.chrome.com/docs/workbox/caching-resources-during-runtime/#opaque-responses).
  66. *
  67. * The message that's posted has the following format (where `payload` can
  68. * be customized via the `generatePayload` option the instance is created
  69. * with):
  70. *
  71. * ```
  72. * {
  73. * type: 'CACHE_UPDATED',
  74. * meta: 'workbox-broadcast-update',
  75. * payload: {
  76. * cacheName: 'the-cache-name',
  77. * updatedURL: 'https://example.com/'
  78. * }
  79. * }
  80. * ```
  81. *
  82. * @param {Object} options
  83. * @param {Response} [options.oldResponse] Cached response to compare.
  84. * @param {Response} options.newResponse Possibly updated response to compare.
  85. * @param {Request} options.request The request.
  86. * @param {string} options.cacheName Name of the cache the responses belong
  87. * to. This is included in the broadcast message.
  88. * @param {Event} options.event event The event that triggered
  89. * this possible cache update.
  90. * @return {Promise} Resolves once the update is sent.
  91. */
  92. async notifyIfUpdated(options) {
  93. if (process.env.NODE_ENV !== 'production') {
  94. assert.isType(options.cacheName, 'string', {
  95. moduleName: 'workbox-broadcast-update',
  96. className: 'BroadcastCacheUpdate',
  97. funcName: 'notifyIfUpdated',
  98. paramName: 'cacheName',
  99. });
  100. assert.isInstance(options.newResponse, Response, {
  101. moduleName: 'workbox-broadcast-update',
  102. className: 'BroadcastCacheUpdate',
  103. funcName: 'notifyIfUpdated',
  104. paramName: 'newResponse',
  105. });
  106. assert.isInstance(options.request, Request, {
  107. moduleName: 'workbox-broadcast-update',
  108. className: 'BroadcastCacheUpdate',
  109. funcName: 'notifyIfUpdated',
  110. paramName: 'request',
  111. });
  112. }
  113. // Without two responses there is nothing to compare.
  114. if (!options.oldResponse) {
  115. return;
  116. }
  117. if (!responsesAreSame(options.oldResponse, options.newResponse, this._headersToCheck)) {
  118. if (process.env.NODE_ENV !== 'production') {
  119. logger.log(`Newer response found (and cached) for:`, options.request.url);
  120. }
  121. const messageData = {
  122. type: CACHE_UPDATED_MESSAGE_TYPE,
  123. meta: CACHE_UPDATED_MESSAGE_META,
  124. payload: this._generatePayload(options),
  125. };
  126. // For navigation requests, wait until the new window client exists
  127. // before sending the message
  128. if (options.request.mode === 'navigate') {
  129. let resultingClientId;
  130. if (options.event instanceof FetchEvent) {
  131. resultingClientId = options.event.resultingClientId;
  132. }
  133. const resultingWin = await resultingClientExists(resultingClientId);
  134. // Safari does not currently implement postMessage buffering and
  135. // there's no good way to feature detect that, so to increase the
  136. // chances of the message being delivered in Safari, we add a timeout.
  137. // We also do this if `resultingClientExists()` didn't return a client,
  138. // which means it timed out, so it's worth waiting a bit longer.
  139. if (!resultingWin || isSafari) {
  140. // 3500 is chosen because (according to CrUX data) 80% of mobile
  141. // websites hit the DOMContentLoaded event in less than 3.5 seconds.
  142. // And presumably sites implementing service worker are on the
  143. // higher end of the performance spectrum.
  144. await timeout(3500);
  145. }
  146. }
  147. if (this._notifyAllClients) {
  148. const windows = await self.clients.matchAll({ type: 'window' });
  149. for (const win of windows) {
  150. win.postMessage(messageData);
  151. }
  152. }
  153. else {
  154. // See https://github.com/GoogleChrome/workbox/issues/2895
  155. if (options.event instanceof FetchEvent) {
  156. const client = await self.clients.get(options.event.clientId);
  157. client === null || client === void 0 ? void 0 : client.postMessage(messageData);
  158. }
  159. }
  160. }
  161. }
  162. }
  163. export { BroadcastCacheUpdate };