workbox-window.dev.umd.js 43 KB

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