Workbox.js 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620
  1. /*
  2. Copyright 2019 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 { Deferred } from 'workbox-core/_private/Deferred.js';
  8. import { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js';
  9. import { logger } from 'workbox-core/_private/logger.js';
  10. import { messageSW } from './messageSW.js';
  11. import { WorkboxEventTarget } from './utils/WorkboxEventTarget.js';
  12. import { urlsMatch } from './utils/urlsMatch.js';
  13. import { WorkboxEvent } from './utils/WorkboxEvent.js';
  14. import './_version.js';
  15. // The time a SW must be in the waiting phase before we can conclude
  16. // `skipWaiting()` wasn't called. This 200 amount wasn't scientifically
  17. // chosen, but it seems to avoid false positives in my testing.
  18. const WAITING_TIMEOUT_DURATION = 200;
  19. // The amount of time after a registration that we can reasonably conclude
  20. // that the registration didn't trigger an update.
  21. const REGISTRATION_TIMEOUT_DURATION = 60000;
  22. // The de facto standard message that a service worker should be listening for
  23. // to trigger a call to skipWaiting().
  24. const SKIP_WAITING_MESSAGE = { type: 'SKIP_WAITING' };
  25. /**
  26. * A class to aid in handling service worker registration, updates, and
  27. * reacting to service worker lifecycle events.
  28. *
  29. * @fires {@link workbox-window.Workbox#message}
  30. * @fires {@link workbox-window.Workbox#installed}
  31. * @fires {@link workbox-window.Workbox#waiting}
  32. * @fires {@link workbox-window.Workbox#controlling}
  33. * @fires {@link workbox-window.Workbox#activated}
  34. * @fires {@link workbox-window.Workbox#redundant}
  35. * @memberof workbox-window
  36. */
  37. class Workbox extends WorkboxEventTarget {
  38. /**
  39. * Creates a new Workbox instance with a script URL and service worker
  40. * options. The script URL and options are the same as those used when
  41. * calling [navigator.serviceWorker.register(scriptURL, options)](https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register).
  42. *
  43. * @param {string|TrustedScriptURL} scriptURL The service worker script
  44. * associated with this instance. Using a
  45. * [`TrustedScriptURL`](https://web.dev/trusted-types/) is supported.
  46. * @param {Object} [registerOptions] The service worker options associated
  47. * with this instance.
  48. */
  49. // eslint-disable-next-line @typescript-eslint/ban-types
  50. constructor(scriptURL, registerOptions = {}) {
  51. super();
  52. this._registerOptions = {};
  53. this._updateFoundCount = 0;
  54. // Deferreds we can resolve later.
  55. this._swDeferred = new Deferred();
  56. this._activeDeferred = new Deferred();
  57. this._controllingDeferred = new Deferred();
  58. this._registrationTime = 0;
  59. this._ownSWs = new Set();
  60. /**
  61. * @private
  62. */
  63. this._onUpdateFound = () => {
  64. // `this._registration` will never be `undefined` after an update is found.
  65. const registration = this._registration;
  66. const installingSW = registration.installing;
  67. // If the script URL passed to `navigator.serviceWorker.register()` is
  68. // different from the current controlling SW's script URL, we know any
  69. // successful registration calls will trigger an `updatefound` event.
  70. // But if the registered script URL is the same as the current controlling
  71. // SW's script URL, we'll only get an `updatefound` event if the file
  72. // changed since it was last registered. This can be a problem if the user
  73. // opens up the same page in a different tab, and that page registers
  74. // a SW that triggers an update. It's a problem because this page has no
  75. // good way of knowing whether the `updatefound` event came from the SW
  76. // script it registered or from a registration attempt made by a newer
  77. // version of the page running in another tab.
  78. // To minimize the possibility of a false positive, we use the logic here:
  79. const updateLikelyTriggeredExternally =
  80. // Since we enforce only calling `register()` once, and since we don't
  81. // add the `updatefound` event listener until the `register()` call, if
  82. // `_updateFoundCount` is > 0 then it means this method has already
  83. // been called, thus this SW must be external
  84. this._updateFoundCount > 0 ||
  85. // If the script URL of the installing SW is different from this
  86. // instance's script URL, we know it's definitely not from our
  87. // registration.
  88. !urlsMatch(installingSW.scriptURL, this._scriptURL.toString()) ||
  89. // If all of the above are false, then we use a time-based heuristic:
  90. // Any `updatefound` event that occurs long after our registration is
  91. // assumed to be external.
  92. performance.now() > this._registrationTime + REGISTRATION_TIMEOUT_DURATION
  93. ? // If any of the above are not true, we assume the update was
  94. // triggered by this instance.
  95. true
  96. : false;
  97. if (updateLikelyTriggeredExternally) {
  98. this._externalSW = installingSW;
  99. registration.removeEventListener('updatefound', this._onUpdateFound);
  100. }
  101. else {
  102. // If the update was not triggered externally we know the installing
  103. // SW is the one we registered, so we set it.
  104. this._sw = installingSW;
  105. this._ownSWs.add(installingSW);
  106. this._swDeferred.resolve(installingSW);
  107. // The `installing` state isn't something we have a dedicated
  108. // callback for, but we do log messages for it in development.
  109. if (process.env.NODE_ENV !== 'production') {
  110. if (navigator.serviceWorker.controller) {
  111. logger.log('Updated service worker found. Installing now...');
  112. }
  113. else {
  114. logger.log('Service worker is installing...');
  115. }
  116. }
  117. }
  118. // Increment the `updatefound` count, so future invocations of this
  119. // method can be sure they were triggered externally.
  120. ++this._updateFoundCount;
  121. // Add a `statechange` listener regardless of whether this update was
  122. // triggered externally, since we have callbacks for both.
  123. installingSW.addEventListener('statechange', this._onStateChange);
  124. };
  125. /**
  126. * @private
  127. * @param {Event} originalEvent
  128. */
  129. this._onStateChange = (originalEvent) => {
  130. // `this._registration` will never be `undefined` after an update is found.
  131. const registration = this._registration;
  132. const sw = originalEvent.target;
  133. const { state } = sw;
  134. const isExternal = sw === this._externalSW;
  135. const eventProps = {
  136. sw,
  137. isExternal,
  138. originalEvent,
  139. };
  140. if (!isExternal && this._isUpdate) {
  141. eventProps.isUpdate = true;
  142. }
  143. this.dispatchEvent(new WorkboxEvent(state, eventProps));
  144. if (state === 'installed') {
  145. // This timeout is used to ignore cases where the service worker calls
  146. // `skipWaiting()` in the install event, thus moving it directly in the
  147. // activating state. (Since all service workers *must* go through the
  148. // waiting phase, the only way to detect `skipWaiting()` called in the
  149. // install event is to observe that the time spent in the waiting phase
  150. // is very short.)
  151. // NOTE: we don't need separate timeouts for the own and external SWs
  152. // since they can't go through these phases at the same time.
  153. this._waitingTimeout = self.setTimeout(() => {
  154. // Ensure the SW is still waiting (it may now be redundant).
  155. if (state === 'installed' && registration.waiting === sw) {
  156. this.dispatchEvent(new WorkboxEvent('waiting', eventProps));
  157. if (process.env.NODE_ENV !== 'production') {
  158. if (isExternal) {
  159. logger.warn('An external service worker has installed but is ' +
  160. 'waiting for this client to close before activating...');
  161. }
  162. else {
  163. logger.warn('The service worker has installed but is waiting ' +
  164. 'for existing clients to close before activating...');
  165. }
  166. }
  167. }
  168. }, WAITING_TIMEOUT_DURATION);
  169. }
  170. else if (state === 'activating') {
  171. clearTimeout(this._waitingTimeout);
  172. if (!isExternal) {
  173. this._activeDeferred.resolve(sw);
  174. }
  175. }
  176. if (process.env.NODE_ENV !== 'production') {
  177. switch (state) {
  178. case 'installed':
  179. if (isExternal) {
  180. logger.warn('An external service worker has installed. ' +
  181. 'You may want to suggest users reload this page.');
  182. }
  183. else {
  184. logger.log('Registered service worker installed.');
  185. }
  186. break;
  187. case 'activated':
  188. if (isExternal) {
  189. logger.warn('An external service worker has activated.');
  190. }
  191. else {
  192. logger.log('Registered service worker activated.');
  193. if (sw !== navigator.serviceWorker.controller) {
  194. logger.warn('The registered service worker is active but ' +
  195. 'not yet controlling the page. Reload or run ' +
  196. '`clients.claim()` in the service worker.');
  197. }
  198. }
  199. break;
  200. case 'redundant':
  201. if (sw === this._compatibleControllingSW) {
  202. logger.log('Previously controlling service worker now redundant!');
  203. }
  204. else if (!isExternal) {
  205. logger.log('Registered service worker now redundant!');
  206. }
  207. break;
  208. }
  209. }
  210. };
  211. /**
  212. * @private
  213. * @param {Event} originalEvent
  214. */
  215. this._onControllerChange = (originalEvent) => {
  216. const sw = this._sw;
  217. const isExternal = sw !== navigator.serviceWorker.controller;
  218. // Unconditionally dispatch the controlling event, with isExternal set
  219. // to distinguish between controller changes due to the initial registration
  220. // vs. an update-check or other tab's registration.
  221. // See https://github.com/GoogleChrome/workbox/issues/2786
  222. this.dispatchEvent(new WorkboxEvent('controlling', {
  223. isExternal,
  224. originalEvent,
  225. sw,
  226. isUpdate: this._isUpdate,
  227. }));
  228. if (!isExternal) {
  229. if (process.env.NODE_ENV !== 'production') {
  230. logger.log('Registered service worker now controlling this page.');
  231. }
  232. this._controllingDeferred.resolve(sw);
  233. }
  234. };
  235. /**
  236. * @private
  237. * @param {Event} originalEvent
  238. */
  239. this._onMessage = async (originalEvent) => {
  240. // Can't change type 'any' of data.
  241. // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
  242. const { data, ports, source } = originalEvent;
  243. // Wait until there's an "own" service worker. This is used to buffer
  244. // `message` events that may be received prior to calling `register()`.
  245. await this.getSW();
  246. // If the service worker that sent the message is in the list of own
  247. // service workers for this instance, dispatch a `message` event.
  248. // NOTE: we check for all previously owned service workers rather than
  249. // just the current one because some messages (e.g. cache updates) use
  250. // a timeout when sent and may be delayed long enough for a service worker
  251. // update to be found.
  252. if (this._ownSWs.has(source)) {
  253. this.dispatchEvent(new WorkboxEvent('message', {
  254. // Can't change type 'any' of data.
  255. // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
  256. data,
  257. originalEvent,
  258. ports,
  259. sw: source,
  260. }));
  261. }
  262. };
  263. this._scriptURL = scriptURL;
  264. this._registerOptions = registerOptions;
  265. // Add a message listener immediately since messages received during
  266. // page load are buffered only until the DOMContentLoaded event:
  267. // https://github.com/GoogleChrome/workbox/issues/2202
  268. navigator.serviceWorker.addEventListener('message', this._onMessage);
  269. }
  270. /**
  271. * Registers a service worker for this instances script URL and service
  272. * worker options. By default this method delays registration until after
  273. * the window has loaded.
  274. *
  275. * @param {Object} [options]
  276. * @param {Function} [options.immediate=false] Setting this to true will
  277. * register the service worker immediately, even if the window has
  278. * not loaded (not recommended).
  279. */
  280. async register({ immediate = false } = {}) {
  281. if (process.env.NODE_ENV !== 'production') {
  282. if (this._registrationTime) {
  283. logger.error('Cannot re-register a Workbox instance after it has ' +
  284. 'been registered. Create a new instance instead.');
  285. return;
  286. }
  287. }
  288. if (!immediate && document.readyState !== 'complete') {
  289. await new Promise((res) => window.addEventListener('load', res));
  290. }
  291. // Set this flag to true if any service worker was controlling the page
  292. // at registration time.
  293. this._isUpdate = Boolean(navigator.serviceWorker.controller);
  294. // Before registering, attempt to determine if a SW is already controlling
  295. // the page, and if that SW script (and version, if specified) matches this
  296. // instance's script.
  297. this._compatibleControllingSW = this._getControllingSWIfCompatible();
  298. this._registration = await this._registerScript();
  299. // If we have a compatible controller, store the controller as the "own"
  300. // SW, resolve active/controlling deferreds and add necessary listeners.
  301. if (this._compatibleControllingSW) {
  302. this._sw = this._compatibleControllingSW;
  303. this._activeDeferred.resolve(this._compatibleControllingSW);
  304. this._controllingDeferred.resolve(this._compatibleControllingSW);
  305. this._compatibleControllingSW.addEventListener('statechange', this._onStateChange, { once: true });
  306. }
  307. // If there's a waiting service worker with a matching URL before the
  308. // `updatefound` event fires, it likely means that this site is open
  309. // in another tab, or the user refreshed the page (and thus the previous
  310. // page wasn't fully unloaded before this page started loading).
  311. // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting
  312. const waitingSW = this._registration.waiting;
  313. if (waitingSW &&
  314. urlsMatch(waitingSW.scriptURL, this._scriptURL.toString())) {
  315. // Store the waiting SW as the "own" Sw, even if it means overwriting
  316. // a compatible controller.
  317. this._sw = waitingSW;
  318. // Run this in the next microtask, so any code that adds an event
  319. // listener after awaiting `register()` will get this event.
  320. dontWaitFor(Promise.resolve().then(() => {
  321. this.dispatchEvent(new WorkboxEvent('waiting', {
  322. sw: waitingSW,
  323. wasWaitingBeforeRegister: true,
  324. }));
  325. if (process.env.NODE_ENV !== 'production') {
  326. logger.warn('A service worker was already waiting to activate ' +
  327. 'before this script was registered...');
  328. }
  329. }));
  330. }
  331. // If an "own" SW is already set, resolve the deferred.
  332. if (this._sw) {
  333. this._swDeferred.resolve(this._sw);
  334. this._ownSWs.add(this._sw);
  335. }
  336. if (process.env.NODE_ENV !== 'production') {
  337. logger.log('Successfully registered service worker.', this._scriptURL.toString());
  338. if (navigator.serviceWorker.controller) {
  339. if (this._compatibleControllingSW) {
  340. logger.debug('A service worker with the same script URL ' +
  341. 'is already controlling this page.');
  342. }
  343. else {
  344. logger.debug('A service worker with a different script URL is ' +
  345. 'currently controlling the page. The browser is now fetching ' +
  346. 'the new script now...');
  347. }
  348. }
  349. const currentPageIsOutOfScope = () => {
  350. const scopeURL = new URL(this._registerOptions.scope || this._scriptURL.toString(), document.baseURI);
  351. const scopeURLBasePath = new URL('./', scopeURL.href).pathname;
  352. return !location.pathname.startsWith(scopeURLBasePath);
  353. };
  354. if (currentPageIsOutOfScope()) {
  355. logger.warn('The current page is not in scope for the registered ' +
  356. 'service worker. Was this a mistake?');
  357. }
  358. }
  359. this._registration.addEventListener('updatefound', this._onUpdateFound);
  360. navigator.serviceWorker.addEventListener('controllerchange', this._onControllerChange);
  361. return this._registration;
  362. }
  363. /**
  364. * Checks for updates of the registered service worker.
  365. */
  366. async update() {
  367. if (!this._registration) {
  368. if (process.env.NODE_ENV !== 'production') {
  369. logger.error('Cannot update a Workbox instance without ' +
  370. 'being registered. Register the Workbox instance first.');
  371. }
  372. return;
  373. }
  374. // Try to update registration
  375. await this._registration.update();
  376. }
  377. /**
  378. * Resolves to the service worker registered by this instance as soon as it
  379. * is active. If a service worker was already controlling at registration
  380. * time then it will resolve to that if the script URLs (and optionally
  381. * script versions) match, otherwise it will wait until an update is found
  382. * and activates.
  383. *
  384. * @return {Promise<ServiceWorker>}
  385. */
  386. get active() {
  387. return this._activeDeferred.promise;
  388. }
  389. /**
  390. * Resolves to the service worker registered by this instance as soon as it
  391. * is controlling the page. If a service worker was already controlling at
  392. * registration time then it will resolve to that if the script URLs (and
  393. * optionally script versions) match, otherwise it will wait until an update
  394. * is found and starts controlling the page.
  395. * Note: the first time a service worker is installed it will active but
  396. * not start controlling the page unless `clients.claim()` is called in the
  397. * service worker.
  398. *
  399. * @return {Promise<ServiceWorker>}
  400. */
  401. get controlling() {
  402. return this._controllingDeferred.promise;
  403. }
  404. /**
  405. * Resolves with a reference to a service worker that matches the script URL
  406. * of this instance, as soon as it's available.
  407. *
  408. * If, at registration time, there's already an active or waiting service
  409. * worker with a matching script URL, it will be used (with the waiting
  410. * service worker taking precedence over the active service worker if both
  411. * match, since the waiting service worker would have been registered more
  412. * recently).
  413. * If there's no matching active or waiting service worker at registration
  414. * time then the promise will not resolve until an update is found and starts
  415. * installing, at which point the installing service worker is used.
  416. *
  417. * @return {Promise<ServiceWorker>}
  418. */
  419. getSW() {
  420. // If `this._sw` is set, resolve with that as we want `getSW()` to
  421. // return the correct (new) service worker if an update is found.
  422. return this._sw !== undefined
  423. ? Promise.resolve(this._sw)
  424. : this._swDeferred.promise;
  425. }
  426. /**
  427. * Sends the passed data object to the service worker registered by this
  428. * instance (via {@link workbox-window.Workbox#getSW}) and resolves
  429. * with a response (if any).
  430. *
  431. * A response can be set in a message handler in the service worker by
  432. * calling `event.ports[0].postMessage(...)`, which will resolve the promise
  433. * returned by `messageSW()`. If no response is set, the promise will never
  434. * resolve.
  435. *
  436. * @param {Object} data An object to send to the service worker
  437. * @return {Promise<Object>}
  438. */
  439. // We might be able to change the 'data' type to Record<string, unknown> in the future.
  440. // eslint-disable-next-line @typescript-eslint/ban-types
  441. async messageSW(data) {
  442. const sw = await this.getSW();
  443. return messageSW(sw, data);
  444. }
  445. /**
  446. * Sends a `{type: 'SKIP_WAITING'}` message to the service worker that's
  447. * currently in the `waiting` state associated with the current registration.
  448. *
  449. * If there is no current registration or no service worker is `waiting`,
  450. * calling this will have no effect.
  451. */
  452. messageSkipWaiting() {
  453. if (this._registration && this._registration.waiting) {
  454. void messageSW(this._registration.waiting, SKIP_WAITING_MESSAGE);
  455. }
  456. }
  457. /**
  458. * Checks for a service worker already controlling the page and returns
  459. * it if its script URL matches.
  460. *
  461. * @private
  462. * @return {ServiceWorker|undefined}
  463. */
  464. _getControllingSWIfCompatible() {
  465. const controller = navigator.serviceWorker.controller;
  466. if (controller &&
  467. urlsMatch(controller.scriptURL, this._scriptURL.toString())) {
  468. return controller;
  469. }
  470. else {
  471. return undefined;
  472. }
  473. }
  474. /**
  475. * Registers a service worker for this instances script URL and register
  476. * options and tracks the time registration was complete.
  477. *
  478. * @private
  479. */
  480. async _registerScript() {
  481. try {
  482. // this._scriptURL may be a TrustedScriptURL, but there's no support for
  483. // passing that to register() in lib.dom right now.
  484. // https://github.com/GoogleChrome/workbox/issues/2855
  485. const reg = await navigator.serviceWorker.register(this._scriptURL, this._registerOptions);
  486. // Keep track of when registration happened, so it can be used in the
  487. // `this._onUpdateFound` heuristic. Also use the presence of this
  488. // property as a way to see if `.register()` has been called.
  489. this._registrationTime = performance.now();
  490. return reg;
  491. }
  492. catch (error) {
  493. if (process.env.NODE_ENV !== 'production') {
  494. logger.error(error);
  495. }
  496. // Re-throw the error.
  497. throw error;
  498. }
  499. }
  500. }
  501. export { Workbox };
  502. // The jsdoc comments below outline the events this instance may dispatch:
  503. // -----------------------------------------------------------------------
  504. /**
  505. * The `message` event is dispatched any time a `postMessage` is received.
  506. *
  507. * @event workbox-window.Workbox#message
  508. * @type {WorkboxEvent}
  509. * @property {*} data The `data` property from the original `message` event.
  510. * @property {Event} originalEvent The original [`message`]{@link https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent}
  511. * event.
  512. * @property {string} type `message`.
  513. * @property {MessagePort[]} ports The `ports` value from `originalEvent`.
  514. * @property {Workbox} target The `Workbox` instance.
  515. */
  516. /**
  517. * The `installed` event is dispatched if the state of a
  518. * {@link workbox-window.Workbox} instance's
  519. * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}
  520. * changes to `installed`.
  521. *
  522. * Then can happen either the very first time a service worker is installed,
  523. * or after an update to the current service worker is found. In the case
  524. * of an update being found, the event's `isUpdate` property will be `true`.
  525. *
  526. * @event workbox-window.Workbox#installed
  527. * @type {WorkboxEvent}
  528. * @property {ServiceWorker} sw The service worker instance.
  529. * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}
  530. * event.
  531. * @property {boolean|undefined} isUpdate True if a service worker was already
  532. * controlling when this `Workbox` instance called `register()`.
  533. * @property {boolean|undefined} isExternal True if this event is associated
  534. * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.
  535. * @property {string} type `installed`.
  536. * @property {Workbox} target The `Workbox` instance.
  537. */
  538. /**
  539. * The `waiting` event is dispatched if the state of a
  540. * {@link workbox-window.Workbox} instance's
  541. * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}
  542. * changes to `installed` and then doesn't immediately change to `activating`.
  543. * It may also be dispatched if a service worker with the same
  544. * [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}
  545. * was already waiting when the {@link workbox-window.Workbox#register}
  546. * method was called.
  547. *
  548. * @event workbox-window.Workbox#waiting
  549. * @type {WorkboxEvent}
  550. * @property {ServiceWorker} sw The service worker instance.
  551. * @property {Event|undefined} originalEvent The original
  552. * [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}
  553. * event, or `undefined` in the case where the service worker was waiting
  554. * to before `.register()` was called.
  555. * @property {boolean|undefined} isUpdate True if a service worker was already
  556. * controlling when this `Workbox` instance called `register()`.
  557. * @property {boolean|undefined} isExternal True if this event is associated
  558. * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.
  559. * @property {boolean|undefined} wasWaitingBeforeRegister True if a service worker with
  560. * a matching `scriptURL` was already waiting when this `Workbox`
  561. * instance called `register()`.
  562. * @property {string} type `waiting`.
  563. * @property {Workbox} target The `Workbox` instance.
  564. */
  565. /**
  566. * The `controlling` event is dispatched if a
  567. * [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}
  568. * fires on the service worker [container]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer}
  569. * and the [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}
  570. * of the new [controller]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/controller}
  571. * matches the `scriptURL` of the `Workbox` instance's
  572. * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}.
  573. *
  574. * @event workbox-window.Workbox#controlling
  575. * @type {WorkboxEvent}
  576. * @property {ServiceWorker} sw The service worker instance.
  577. * @property {Event} originalEvent The original [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}
  578. * event.
  579. * @property {boolean|undefined} isUpdate True if a service worker was already
  580. * controlling when this service worker was registered.
  581. * @property {boolean|undefined} isExternal True if this event is associated
  582. * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.
  583. * @property {string} type `controlling`.
  584. * @property {Workbox} target The `Workbox` instance.
  585. */
  586. /**
  587. * The `activated` event is dispatched if the state of a
  588. * {@link workbox-window.Workbox} instance's
  589. * {@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw|registered service worker}
  590. * changes to `activated`.
  591. *
  592. * @event workbox-window.Workbox#activated
  593. * @type {WorkboxEvent}
  594. * @property {ServiceWorker} sw The service worker instance.
  595. * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}
  596. * event.
  597. * @property {boolean|undefined} isUpdate True if a service worker was already
  598. * controlling when this `Workbox` instance called `register()`.
  599. * @property {boolean|undefined} isExternal True if this event is associated
  600. * with an [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}.
  601. * @property {string} type `activated`.
  602. * @property {Workbox} target The `Workbox` instance.
  603. */
  604. /**
  605. * The `redundant` event is dispatched if the state of a
  606. * {@link workbox-window.Workbox} instance's
  607. * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}
  608. * changes to `redundant`.
  609. *
  610. * @event workbox-window.Workbox#redundant
  611. * @type {WorkboxEvent}
  612. * @property {ServiceWorker} sw The service worker instance.
  613. * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}
  614. * event.
  615. * @property {boolean|undefined} isUpdate True if a service worker was already
  616. * controlling when this `Workbox` instance called `register()`.
  617. * @property {string} type `redundant`.
  618. * @property {Workbox} target The `Workbox` instance.
  619. */