workbox-window.dev.mjs 24 KB

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