workbox-window.dev.mjs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943
  1. try {
  2. self['workbox:window:5.1.4'] && _();
  3. } catch (e) {}
  4. /*
  5. Copyright 2019 Google LLC
  6. Use of this source code is governed by an MIT-style
  7. license that can be found in the LICENSE file or at
  8. https://opensource.org/licenses/MIT.
  9. */
  10. /**
  11. * Sends a data object to a service worker via `postMessage` and resolves with
  12. * a response (if any).
  13. *
  14. * A response can be set in a message handler in the service worker by
  15. * calling `event.ports[0].postMessage(...)`, which will resolve the promise
  16. * returned by `messageSW()`. If no response is set, the promise will not
  17. * resolve.
  18. *
  19. * @param {ServiceWorker} sw The service worker to send the message to.
  20. * @param {Object} data An object to send to the service worker.
  21. * @return {Promise<Object|undefined>}
  22. * @memberof module:workbox-window
  23. */
  24. function messageSW(sw, data) {
  25. return new Promise(resolve => {
  26. const messageChannel = new MessageChannel();
  27. messageChannel.port1.onmessage = event => {
  28. resolve(event.data);
  29. };
  30. sw.postMessage(data, [messageChannel.port2]);
  31. });
  32. }
  33. try {
  34. self['workbox:core:5.1.4'] && _();
  35. } catch (e) {}
  36. /*
  37. Copyright 2018 Google LLC
  38. Use of this source code is governed by an MIT-style
  39. license that can be found in the LICENSE file or at
  40. https://opensource.org/licenses/MIT.
  41. */
  42. /**
  43. * The Deferred class composes Promises in a way that allows for them to be
  44. * resolved or rejected from outside the constructor. In most cases promises
  45. * should be used directly, but Deferreds can be necessary when the logic to
  46. * resolve a promise must be separate.
  47. *
  48. * @private
  49. */
  50. class Deferred {
  51. /**
  52. * Creates a promise and exposes its resolve and reject functions as methods.
  53. */
  54. constructor() {
  55. this.promise = new Promise((resolve, reject) => {
  56. this.resolve = resolve;
  57. this.reject = reject;
  58. });
  59. }
  60. }
  61. /*
  62. Copyright 2019 Google LLC
  63. Use of this source code is governed by an MIT-style
  64. license that can be found in the LICENSE file or at
  65. https://opensource.org/licenses/MIT.
  66. */
  67. /**
  68. * A helper function that prevents a promise from being flagged as unused.
  69. *
  70. * @private
  71. **/
  72. function dontWaitFor(promise) {
  73. // Effective no-op.
  74. promise.then(() => {});
  75. }
  76. /*
  77. Copyright 2019 Google LLC
  78. Use of this source code is governed by an MIT-style
  79. license that can be found in the LICENSE file or at
  80. https://opensource.org/licenses/MIT.
  81. */
  82. const logger = (() => {
  83. // Don't overwrite this value if it's already set.
  84. // See https://github.com/GoogleChrome/workbox/pull/2284#issuecomment-560470923
  85. if (!('__WB_DISABLE_DEV_LOGS' in self)) {
  86. self.__WB_DISABLE_DEV_LOGS = false;
  87. }
  88. let inGroup = false;
  89. const methodToColorMap = {
  90. debug: `#7f8c8d`,
  91. log: `#2ecc71`,
  92. warn: `#f39c12`,
  93. error: `#c0392b`,
  94. groupCollapsed: `#3498db`,
  95. groupEnd: null
  96. };
  97. const print = function (method, args) {
  98. if (self.__WB_DISABLE_DEV_LOGS) {
  99. return;
  100. }
  101. if (method === 'groupCollapsed') {
  102. // Safari doesn't print all console.groupCollapsed() arguments:
  103. // https://bugs.webkit.org/show_bug.cgi?id=182754
  104. if (/^((?!chrome|android).)*safari/i.test(navigator.userAgent)) {
  105. console[method](...args);
  106. return;
  107. }
  108. }
  109. const styles = [`background: ${methodToColorMap[method]}`, `border-radius: 0.5em`, `color: white`, `font-weight: bold`, `padding: 2px 0.5em`]; // When in a group, the workbox prefix is not displayed.
  110. const logPrefix = inGroup ? [] : ['%cworkbox', styles.join(';')];
  111. console[method](...logPrefix, ...args);
  112. if (method === 'groupCollapsed') {
  113. inGroup = true;
  114. }
  115. if (method === 'groupEnd') {
  116. inGroup = false;
  117. }
  118. };
  119. const api = {};
  120. const loggerMethods = Object.keys(methodToColorMap);
  121. for (const key of loggerMethods) {
  122. const method = key;
  123. api[method] = (...args) => {
  124. print(method, args);
  125. };
  126. }
  127. return api;
  128. })();
  129. /*
  130. Copyright 2019 Google LLC
  131. Use of this source code is governed by an MIT-style
  132. license that can be found in the LICENSE file or at
  133. https://opensource.org/licenses/MIT.
  134. */
  135. /**
  136. * A minimal `EventTarget` shim.
  137. * This is necessary because not all browsers support constructable
  138. * `EventTarget`, so using a real `EventTarget` will error.
  139. * @private
  140. */
  141. class WorkboxEventTarget {
  142. constructor() {
  143. this._eventListenerRegistry = new Map();
  144. }
  145. /**
  146. * @param {string} type
  147. * @param {Function} listener
  148. * @private
  149. */
  150. addEventListener(type, listener) {
  151. const foo = this._getEventListenersByType(type);
  152. foo.add(listener);
  153. }
  154. /**
  155. * @param {string} type
  156. * @param {Function} listener
  157. * @private
  158. */
  159. removeEventListener(type, listener) {
  160. this._getEventListenersByType(type).delete(listener);
  161. }
  162. /**
  163. * @param {Object} event
  164. * @private
  165. */
  166. dispatchEvent(event) {
  167. event.target = this;
  168. const listeners = this._getEventListenersByType(event.type);
  169. for (const listener of listeners) {
  170. listener(event);
  171. }
  172. }
  173. /**
  174. * Returns a Set of listeners associated with the passed event type.
  175. * If no handlers have been registered, an empty Set is returned.
  176. *
  177. * @param {string} type The event type.
  178. * @return {Set<ListenerCallback>} An array of handler functions.
  179. * @private
  180. */
  181. _getEventListenersByType(type) {
  182. if (!this._eventListenerRegistry.has(type)) {
  183. this._eventListenerRegistry.set(type, new Set());
  184. }
  185. return this._eventListenerRegistry.get(type);
  186. }
  187. }
  188. /*
  189. Copyright 2019 Google LLC
  190. Use of this source code is governed by an MIT-style
  191. license that can be found in the LICENSE file or at
  192. https://opensource.org/licenses/MIT.
  193. */
  194. /**
  195. * Returns true if two URLs have the same `.href` property. The URLS can be
  196. * relative, and if they are the current location href is used to resolve URLs.
  197. *
  198. * @private
  199. * @param {string} url1
  200. * @param {string} url2
  201. * @return {boolean}
  202. */
  203. function urlsMatch(url1, url2) {
  204. const {
  205. href
  206. } = location;
  207. return new URL(url1, href).href === new URL(url2, href).href;
  208. }
  209. /*
  210. Copyright 2019 Google LLC
  211. Use of this source code is governed by an MIT-style
  212. license that can be found in the LICENSE file or at
  213. https://opensource.org/licenses/MIT.
  214. */
  215. /**
  216. * A minimal `Event` subclass shim.
  217. * This doesn't *actually* subclass `Event` because not all browsers support
  218. * constructable `EventTarget`, and using a real `Event` will error.
  219. * @private
  220. */
  221. class WorkboxEvent {
  222. constructor(type, props) {
  223. this.type = type;
  224. Object.assign(this, props);
  225. }
  226. }
  227. /*
  228. Copyright 2019 Google LLC
  229. Use of this source code is governed by an MIT-style
  230. license that can be found in the LICENSE file or at
  231. https://opensource.org/licenses/MIT.
  232. */
  233. // `skipWaiting()` wasn't called. This 200 amount wasn't scientifically
  234. // chosen, but it seems to avoid false positives in my testing.
  235. const WAITING_TIMEOUT_DURATION = 200; // The amount of time after a registration that we can reasonably conclude
  236. // that the registration didn't trigger an update.
  237. const REGISTRATION_TIMEOUT_DURATION = 60000;
  238. /**
  239. * A class to aid in handling service worker registration, updates, and
  240. * reacting to service worker lifecycle events.
  241. *
  242. * @fires [message]{@link module:workbox-window.Workbox#message}
  243. * @fires [installed]{@link module:workbox-window.Workbox#installed}
  244. * @fires [waiting]{@link module:workbox-window.Workbox#waiting}
  245. * @fires [controlling]{@link module:workbox-window.Workbox#controlling}
  246. * @fires [activated]{@link module:workbox-window.Workbox#activated}
  247. * @fires [redundant]{@link module:workbox-window.Workbox#redundant}
  248. * @fires [externalinstalled]{@link module:workbox-window.Workbox#externalinstalled}
  249. * @fires [externalwaiting]{@link module:workbox-window.Workbox#externalwaiting}
  250. * @fires [externalactivated]{@link module:workbox-window.Workbox#externalactivated}
  251. * @memberof module:workbox-window
  252. */
  253. class Workbox extends WorkboxEventTarget {
  254. /**
  255. * Creates a new Workbox instance with a script URL and service worker
  256. * options. The script URL and options are the same as those used when
  257. * calling `navigator.serviceWorker.register(scriptURL, options)`. See:
  258. * https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/register
  259. *
  260. * @param {string} scriptURL The service worker script associated with this
  261. * instance.
  262. * @param {Object} [registerOptions] The service worker options associated
  263. * with this instance.
  264. */
  265. constructor(scriptURL, registerOptions = {}) {
  266. super();
  267. this._registerOptions = {};
  268. this._updateFoundCount = 0; // Deferreds we can resolve later.
  269. this._swDeferred = new Deferred();
  270. this._activeDeferred = new Deferred();
  271. this._controllingDeferred = new Deferred();
  272. this._registrationTime = 0;
  273. this._ownSWs = new Set();
  274. /**
  275. * @private
  276. */
  277. this._onUpdateFound = () => {
  278. // `this._registration` will never be `undefined` after an update is found.
  279. const registration = this._registration;
  280. const installingSW = registration.installing; // If the script URL passed to `navigator.serviceWorker.register()` is
  281. // different from the current controlling SW's script URL, we know any
  282. // successful registration calls will trigger an `updatefound` event.
  283. // But if the registered script URL is the same as the current controlling
  284. // SW's script URL, we'll only get an `updatefound` event if the file
  285. // changed since it was last registered. This can be a problem if the user
  286. // opens up the same page in a different tab, and that page registers
  287. // a SW that triggers an update. It's a problem because this page has no
  288. // good way of knowing whether the `updatefound` event came from the SW
  289. // script it registered or from a registration attempt made by a newer
  290. // version of the page running in another tab.
  291. // To minimize the possibility of a false positive, we use the logic here:
  292. const updateLikelyTriggeredExternally = // Since we enforce only calling `register()` once, and since we don't
  293. // add the `updatefound` event listener until the `register()` call, if
  294. // `_updateFoundCount` is > 0 then it means this method has already
  295. // been called, thus this SW must be external
  296. this._updateFoundCount > 0 || // If the script URL of the installing SW is different from this
  297. // instance's script URL, we know it's definitely not from our
  298. // registration.
  299. !urlsMatch(installingSW.scriptURL, this._scriptURL) || // If all of the above are false, then we use a time-based heuristic:
  300. // Any `updatefound` event that occurs long after our registration is
  301. // assumed to be external.
  302. performance.now() > this._registrationTime + REGISTRATION_TIMEOUT_DURATION ? // If any of the above are not true, we assume the update was
  303. // triggered by this instance.
  304. true : false;
  305. if (updateLikelyTriggeredExternally) {
  306. this._externalSW = installingSW;
  307. registration.removeEventListener('updatefound', this._onUpdateFound);
  308. } else {
  309. // If the update was not triggered externally we know the installing
  310. // SW is the one we registered, so we set it.
  311. this._sw = installingSW;
  312. this._ownSWs.add(installingSW);
  313. this._swDeferred.resolve(installingSW); // The `installing` state isn't something we have a dedicated
  314. // callback for, but we do log messages for it in development.
  315. {
  316. if (navigator.serviceWorker.controller) {
  317. logger.log('Updated service worker found. Installing now...');
  318. } else {
  319. logger.log('Service worker is installing...');
  320. }
  321. }
  322. } // Increment the `updatefound` count, so future invocations of this
  323. // method can be sure they were triggered externally.
  324. ++this._updateFoundCount; // Add a `statechange` listener regardless of whether this update was
  325. // triggered externally, since we have callbacks for both.
  326. installingSW.addEventListener('statechange', this._onStateChange);
  327. };
  328. /**
  329. * @private
  330. * @param {Event} originalEvent
  331. */
  332. this._onStateChange = originalEvent => {
  333. // `this._registration` will never be `undefined` after an update is found.
  334. const registration = this._registration;
  335. const sw = originalEvent.target;
  336. const {
  337. state
  338. } = sw;
  339. const isExternal = sw === this._externalSW;
  340. const eventPrefix = isExternal ? 'external' : '';
  341. const eventProps = {
  342. sw,
  343. originalEvent
  344. };
  345. if (!isExternal && this._isUpdate) {
  346. eventProps.isUpdate = true;
  347. }
  348. this.dispatchEvent(new WorkboxEvent(eventPrefix + state, eventProps));
  349. if (state === 'installed') {
  350. // This timeout is used to ignore cases where the service worker calls
  351. // `skipWaiting()` in the install event, thus moving it directly in the
  352. // activating state. (Since all service workers *must* go through the
  353. // waiting phase, the only way to detect `skipWaiting()` called in the
  354. // install event is to observe that the time spent in the waiting phase
  355. // is very short.)
  356. // NOTE: we don't need separate timeouts for the own and external SWs
  357. // since they can't go through these phases at the same time.
  358. this._waitingTimeout = self.setTimeout(() => {
  359. // Ensure the SW is still waiting (it may now be redundant).
  360. if (state === 'installed' && registration.waiting === sw) {
  361. this.dispatchEvent(new WorkboxEvent(eventPrefix + 'waiting', eventProps));
  362. {
  363. if (isExternal) {
  364. logger.warn('An external service worker has installed but is ' + 'waiting for this client to close before activating...');
  365. } else {
  366. logger.warn('The service worker has installed but is waiting ' + 'for existing clients to close before activating...');
  367. }
  368. }
  369. }
  370. }, WAITING_TIMEOUT_DURATION);
  371. } else if (state === 'activating') {
  372. clearTimeout(this._waitingTimeout);
  373. if (!isExternal) {
  374. this._activeDeferred.resolve(sw);
  375. }
  376. }
  377. {
  378. switch (state) {
  379. case 'installed':
  380. if (isExternal) {
  381. logger.warn('An external service worker has installed. ' + 'You may want to suggest users reload this page.');
  382. } else {
  383. logger.log('Registered service worker installed.');
  384. }
  385. break;
  386. case 'activated':
  387. if (isExternal) {
  388. logger.warn('An external service worker has activated.');
  389. } else {
  390. logger.log('Registered service worker activated.');
  391. if (sw !== navigator.serviceWorker.controller) {
  392. logger.warn('The registered service worker is active but ' + 'not yet controlling the page. Reload or run ' + '`clients.claim()` in the service worker.');
  393. }
  394. }
  395. break;
  396. case 'redundant':
  397. if (sw === this._compatibleControllingSW) {
  398. logger.log('Previously controlling service worker now redundant!');
  399. } else if (!isExternal) {
  400. logger.log('Registered service worker now redundant!');
  401. }
  402. break;
  403. }
  404. }
  405. };
  406. /**
  407. * @private
  408. * @param {Event} originalEvent
  409. */
  410. this._onControllerChange = originalEvent => {
  411. const sw = this._sw;
  412. if (sw === navigator.serviceWorker.controller) {
  413. this.dispatchEvent(new WorkboxEvent('controlling', {
  414. sw,
  415. originalEvent,
  416. isUpdate: this._isUpdate
  417. }));
  418. {
  419. logger.log('Registered service worker now controlling this page.');
  420. }
  421. this._controllingDeferred.resolve(sw);
  422. }
  423. };
  424. /**
  425. * @private
  426. * @param {Event} originalEvent
  427. */
  428. this._onMessage = async originalEvent => {
  429. const {
  430. data,
  431. source
  432. } = originalEvent; // Wait until there's an "own" service worker. This is used to buffer
  433. // `message` events that may be received prior to calling `register()`.
  434. await this.getSW(); // If the service worker that sent the message is in the list of own
  435. // service workers for this instance, dispatch a `message` event.
  436. // NOTE: we check for all previously owned service workers rather than
  437. // just the current one because some messages (e.g. cache updates) use
  438. // a timeout when sent and may be delayed long enough for a service worker
  439. // update to be found.
  440. if (this._ownSWs.has(source)) {
  441. this.dispatchEvent(new WorkboxEvent('message', {
  442. data,
  443. sw: source,
  444. originalEvent
  445. }));
  446. }
  447. };
  448. this._scriptURL = scriptURL;
  449. this._registerOptions = registerOptions; // Add a message listener immediately since messages received during
  450. // page load are buffered only until the DOMContentLoaded event:
  451. // https://github.com/GoogleChrome/workbox/issues/2202
  452. navigator.serviceWorker.addEventListener('message', this._onMessage);
  453. }
  454. /**
  455. * Registers a service worker for this instances script URL and service
  456. * worker options. By default this method delays registration until after
  457. * the window has loaded.
  458. *
  459. * @param {Object} [options]
  460. * @param {Function} [options.immediate=false] Setting this to true will
  461. * register the service worker immediately, even if the window has
  462. * not loaded (not recommended).
  463. */
  464. async register({
  465. immediate = false
  466. } = {}) {
  467. {
  468. if (this._registrationTime) {
  469. logger.error('Cannot re-register a Workbox instance after it has ' + 'been registered. Create a new instance instead.');
  470. return;
  471. }
  472. }
  473. if (!immediate && document.readyState !== 'complete') {
  474. await new Promise(res => window.addEventListener('load', res));
  475. } // Set this flag to true if any service worker was controlling the page
  476. // at registration time.
  477. this._isUpdate = Boolean(navigator.serviceWorker.controller); // Before registering, attempt to determine if a SW is already controlling
  478. // the page, and if that SW script (and version, if specified) matches this
  479. // instance's script.
  480. this._compatibleControllingSW = this._getControllingSWIfCompatible();
  481. this._registration = await this._registerScript(); // If we have a compatible controller, store the controller as the "own"
  482. // SW, resolve active/controlling deferreds and add necessary listeners.
  483. if (this._compatibleControllingSW) {
  484. this._sw = this._compatibleControllingSW;
  485. this._activeDeferred.resolve(this._compatibleControllingSW);
  486. this._controllingDeferred.resolve(this._compatibleControllingSW);
  487. this._compatibleControllingSW.addEventListener('statechange', this._onStateChange, {
  488. once: true
  489. });
  490. } // If there's a waiting service worker with a matching URL before the
  491. // `updatefound` event fires, it likely means that this site is open
  492. // in another tab, or the user refreshed the page (and thus the previous
  493. // page wasn't fully unloaded before this page started loading).
  494. // https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#waiting
  495. const waitingSW = this._registration.waiting;
  496. if (waitingSW && urlsMatch(waitingSW.scriptURL, this._scriptURL)) {
  497. // Store the waiting SW as the "own" Sw, even if it means overwriting
  498. // a compatible controller.
  499. this._sw = waitingSW; // Run this in the next microtask, so any code that adds an event
  500. // listener after awaiting `register()` will get this event.
  501. dontWaitFor(Promise.resolve().then(() => {
  502. this.dispatchEvent(new WorkboxEvent('waiting', {
  503. sw: waitingSW,
  504. wasWaitingBeforeRegister: true
  505. }));
  506. {
  507. logger.warn('A service worker was already waiting to activate ' + 'before this script was registered...');
  508. }
  509. }));
  510. } // If an "own" SW is already set, resolve the deferred.
  511. if (this._sw) {
  512. this._swDeferred.resolve(this._sw);
  513. this._ownSWs.add(this._sw);
  514. }
  515. {
  516. logger.log('Successfully registered service worker.', this._scriptURL);
  517. if (navigator.serviceWorker.controller) {
  518. if (this._compatibleControllingSW) {
  519. logger.debug('A service worker with the same script URL ' + 'is already controlling this page.');
  520. } else {
  521. logger.debug('A service worker with a different script URL is ' + 'currently controlling the page. The browser is now fetching ' + 'the new script now...');
  522. }
  523. }
  524. const currentPageIsOutOfScope = () => {
  525. const scopeURL = new URL(this._registerOptions.scope || this._scriptURL, document.baseURI);
  526. const scopeURLBasePath = new URL('./', scopeURL.href).pathname;
  527. return !location.pathname.startsWith(scopeURLBasePath);
  528. };
  529. if (currentPageIsOutOfScope()) {
  530. logger.warn('The current page is not in scope for the registered ' + 'service worker. Was this a mistake?');
  531. }
  532. }
  533. this._registration.addEventListener('updatefound', this._onUpdateFound);
  534. navigator.serviceWorker.addEventListener('controllerchange', this._onControllerChange, {
  535. once: true
  536. });
  537. return this._registration;
  538. }
  539. /**
  540. * Checks for updates of the registered service worker.
  541. */
  542. async update() {
  543. if (!this._registration) {
  544. {
  545. logger.error('Cannot update a Workbox instance without ' + 'being registered. Register the Workbox instance first.');
  546. }
  547. return;
  548. } // Try to update registration
  549. await this._registration.update();
  550. }
  551. /**
  552. * Resolves to the service worker registered by this instance as soon as it
  553. * is active. If a service worker was already controlling at registration
  554. * time then it will resolve to that if the script URLs (and optionally
  555. * script versions) match, otherwise it will wait until an update is found
  556. * and activates.
  557. *
  558. * @return {Promise<ServiceWorker>}
  559. */
  560. get active() {
  561. return this._activeDeferred.promise;
  562. }
  563. /**
  564. * Resolves to the service worker registered by this instance as soon as it
  565. * is controlling the page. If a service worker was already controlling at
  566. * registration time then it will resolve to that if the script URLs (and
  567. * optionally script versions) match, otherwise it will wait until an update
  568. * is found and starts controlling the page.
  569. * Note: the first time a service worker is installed it will active but
  570. * not start controlling the page unless `clients.claim()` is called in the
  571. * service worker.
  572. *
  573. * @return {Promise<ServiceWorker>}
  574. */
  575. get controlling() {
  576. return this._controllingDeferred.promise;
  577. }
  578. /**
  579. * Resolves with a reference to a service worker that matches the script URL
  580. * of this instance, as soon as it's available.
  581. *
  582. * If, at registration time, there's already an active or waiting service
  583. * worker with a matching script URL, it will be used (with the waiting
  584. * service worker taking precedence over the active service worker if both
  585. * match, since the waiting service worker would have been registered more
  586. * recently).
  587. * If there's no matching active or waiting service worker at registration
  588. * time then the promise will not resolve until an update is found and starts
  589. * installing, at which point the installing service worker is used.
  590. *
  591. * @return {Promise<ServiceWorker>}
  592. */
  593. async getSW() {
  594. // If `this._sw` is set, resolve with that as we want `getSW()` to
  595. // return the correct (new) service worker if an update is found.
  596. return this._sw !== undefined ? this._sw : this._swDeferred.promise;
  597. }
  598. /**
  599. * Sends the passed data object to the service worker registered by this
  600. * instance (via [`getSW()`]{@link module:workbox-window.Workbox#getSW}) and resolves
  601. * with a response (if any).
  602. *
  603. * A response can be set in a message handler in the service worker by
  604. * calling `event.ports[0].postMessage(...)`, which will resolve the promise
  605. * returned by `messageSW()`. If no response is set, the promise will never
  606. * resolve.
  607. *
  608. * @param {Object} data An object to send to the service worker
  609. * @return {Promise<Object>}
  610. */
  611. async messageSW(data) {
  612. const sw = await this.getSW();
  613. return messageSW(sw, data);
  614. }
  615. /**
  616. * Checks for a service worker already controlling the page and returns
  617. * it if its script URL matches.
  618. *
  619. * @private
  620. * @return {ServiceWorker|undefined}
  621. */
  622. _getControllingSWIfCompatible() {
  623. const controller = navigator.serviceWorker.controller;
  624. if (controller && urlsMatch(controller.scriptURL, this._scriptURL)) {
  625. return controller;
  626. } else {
  627. return undefined;
  628. }
  629. }
  630. /**
  631. * Registers a service worker for this instances script URL and register
  632. * options and tracks the time registration was complete.
  633. *
  634. * @private
  635. */
  636. async _registerScript() {
  637. try {
  638. const reg = await navigator.serviceWorker.register(this._scriptURL, this._registerOptions); // Keep track of when registration happened, so it can be used in the
  639. // `this._onUpdateFound` heuristic. Also use the presence of this
  640. // property as a way to see if `.register()` has been called.
  641. this._registrationTime = performance.now();
  642. return reg;
  643. } catch (error) {
  644. {
  645. logger.error(error);
  646. } // Re-throw the error.
  647. throw error;
  648. }
  649. }
  650. }
  651. // -----------------------------------------------------------------------
  652. /**
  653. * The `message` event is dispatched any time a `postMessage` is received.
  654. *
  655. * @event module:workbox-window.Workbox#message
  656. * @type {WorkboxEvent}
  657. * @property {*} data The `data` property from the original `message` event.
  658. * @property {Event} originalEvent The original [`message`]{@link https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent}
  659. * event.
  660. * @property {string} type `message`.
  661. * @property {Workbox} target The `Workbox` instance.
  662. */
  663. /**
  664. * The `installed` event is dispatched if the state of a
  665. * [`Workbox`]{@link module:workbox-window.Workbox} instance's
  666. * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}
  667. * changes to `installed`.
  668. *
  669. * Then can happen either the very first time a service worker is installed,
  670. * or after an update to the current service worker is found. In the case
  671. * of an update being found, the event's `isUpdate` property will be `true`.
  672. *
  673. * @event module:workbox-window.Workbox#installed
  674. * @type {WorkboxEvent}
  675. * @property {ServiceWorker} sw The service worker instance.
  676. * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}
  677. * event.
  678. * @property {boolean|undefined} isUpdate True if a service worker was already
  679. * controlling when this `Workbox` instance called `register()`.
  680. * @property {string} type `installed`.
  681. * @property {Workbox} target The `Workbox` instance.
  682. */
  683. /**
  684. * The `waiting` event is dispatched if the state of a
  685. * [`Workbox`]{@link module:workbox-window.Workbox} instance's
  686. * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}
  687. * changes to `installed` and then doesn't immediately change to `activating`.
  688. * It may also be dispatched if a service worker with the same
  689. * [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}
  690. * was already waiting when the [`register()`]{@link module:workbox-window.Workbox#register}
  691. * method was called.
  692. *
  693. * @event module:workbox-window.Workbox#waiting
  694. * @type {WorkboxEvent}
  695. * @property {ServiceWorker} sw The service worker instance.
  696. * @property {Event|undefined} originalEvent The original
  697. * [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}
  698. * event, or `undefined` in the case where the service worker was waiting
  699. * to before `.register()` was called.
  700. * @property {boolean|undefined} isUpdate True if a service worker was already
  701. * controlling when this `Workbox` instance called `register()`.
  702. * @property {boolean|undefined} wasWaitingBeforeRegister True if a service worker with
  703. * a matching `scriptURL` was already waiting when this `Workbox`
  704. * instance called `register()`.
  705. * @property {string} type `waiting`.
  706. * @property {Workbox} target The `Workbox` instance.
  707. */
  708. /**
  709. * The `controlling` event is dispatched if a
  710. * [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}
  711. * fires on the service worker [container]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer}
  712. * and the [`scriptURL`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/scriptURL}
  713. * of the new [controller]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/controller}
  714. * matches the `scriptURL` of the `Workbox` instance's
  715. * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}.
  716. *
  717. * @event module:workbox-window.Workbox#controlling
  718. * @type {WorkboxEvent}
  719. * @property {ServiceWorker} sw The service worker instance.
  720. * @property {Event} originalEvent The original [`controllerchange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorkerContainer/oncontrollerchange}
  721. * event.
  722. * @property {boolean|undefined} isUpdate True if a service worker was already
  723. * controlling when this service worker was registered.
  724. * @property {string} type `controlling`.
  725. * @property {Workbox} target The `Workbox` instance.
  726. */
  727. /**
  728. * The `activated` event is dispatched if the state of a
  729. * [`Workbox`]{@link module:workbox-window.Workbox} instance's
  730. * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}
  731. * changes to `activated`.
  732. *
  733. * @event module:workbox-window.Workbox#activated
  734. * @type {WorkboxEvent}
  735. * @property {ServiceWorker} sw The service worker instance.
  736. * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}
  737. * event.
  738. * @property {boolean|undefined} isUpdate True if a service worker was already
  739. * controlling when this `Workbox` instance called `register()`.
  740. * @property {string} type `activated`.
  741. * @property {Workbox} target The `Workbox` instance.
  742. */
  743. /**
  744. * The `redundant` event is dispatched if the state of a
  745. * [`Workbox`]{@link module:workbox-window.Workbox} instance's
  746. * [registered service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-precaching#def-registered-sw}
  747. * changes to `redundant`.
  748. *
  749. * @event module:workbox-window.Workbox#redundant
  750. * @type {WorkboxEvent}
  751. * @property {ServiceWorker} sw The service worker instance.
  752. * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}
  753. * event.
  754. * @property {boolean|undefined} isUpdate True if a service worker was already
  755. * controlling when this `Workbox` instance called `register()`.
  756. * @property {string} type `redundant`.
  757. * @property {Workbox} target The `Workbox` instance.
  758. */
  759. /**
  760. * The `externalinstalled` event is dispatched if the state of an
  761. * [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}
  762. * changes to `installed`.
  763. *
  764. * @event module:workbox-window.Workbox#externalinstalled
  765. * @type {WorkboxEvent}
  766. * @property {ServiceWorker} sw The service worker instance.
  767. * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}
  768. * event.
  769. * @property {string} type `externalinstalled`.
  770. * @property {Workbox} target The `Workbox` instance.
  771. */
  772. /**
  773. * The `externalwaiting` event is dispatched if the state of an
  774. * [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}
  775. * changes to `waiting`.
  776. *
  777. * @event module:workbox-window.Workbox#externalwaiting
  778. * @type {WorkboxEvent}
  779. * @property {ServiceWorker} sw The service worker instance.
  780. * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}
  781. * event.
  782. * @property {string} type `externalwaiting`.
  783. * @property {Workbox} target The `Workbox` instance.
  784. */
  785. /**
  786. * The `externalactivated` event is dispatched if the state of an
  787. * [external service worker]{@link https://developers.google.com/web/tools/workbox/modules/workbox-window#when_an_unexpected_version_of_the_service_worker_is_found}
  788. * changes to `activated`.
  789. *
  790. * @event module:workbox-window.Workbox#externalactivated
  791. * @type {WorkboxEvent}
  792. * @property {ServiceWorker} sw The service worker instance.
  793. * @property {Event} originalEvent The original [`statechange`]{@link https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker/onstatechange}
  794. * event.
  795. * @property {string} type `externalactivated`.
  796. * @property {Workbox} target The `Workbox` instance.
  797. */
  798. export { Workbox, messageSW };
  799. //# sourceMappingURL=workbox-window.dev.mjs.map