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