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