fix(service-worker): don't crash if SW not supported

Currently a bug exists where attempting to inject SwPush crashes the
application if Service Workers are unsupported. This happens because
SwPush doesn't properly detect that navigator.serviceWorker isn't
set.

This change ensures that all passive observation of SwPush and
SwUpdate doesn't cause crashes, and that calling methods to perform
actions on them results in rejected Promises. It's up to applications
to detect when those services are not available, and refrain from
attempting to use them.

To that end, this change also adds an `isSupported` getter to both
services, so users don't have to rely on feature detection directly
with browser APIs. Currently this simply detects whether the SW API
is present, but in the future it will be expanded to detect whether
a particular browser supports specific APIs (such as push
notifications, for example).
This commit is contained in:
Alex Rickabaugh
2017-11-30 08:22:41 -08:00
parent 65f4fad801
commit b9a91a5e74
6 changed files with 82 additions and 7 deletions

View File

@ -24,7 +24,7 @@ import {switchMap as op_switchMap} from 'rxjs/operator/switchMap';
import {take as op_take} from 'rxjs/operator/take';
import {toPromise as op_toPromise} from 'rxjs/operator/toPromise';
const ERR_SW_NOT_SUPPORTED = 'Service workers are not supported by this browser';
export const ERR_SW_NOT_SUPPORTED = 'Service workers are disabled or not supported by this browser';
export interface Version {
hash: string;
@ -86,9 +86,9 @@ export class NgswCommChannel {
*/
readonly events: Observable<IncomingEvent>;
constructor(serviceWorker: ServiceWorkerContainer|undefined) {
constructor(private serviceWorker: ServiceWorkerContainer|undefined) {
if (!serviceWorker) {
this.worker = this.events = errorObservable(ERR_SW_NOT_SUPPORTED);
this.worker = this.events = this.registration = errorObservable(ERR_SW_NOT_SUPPORTED);
} else {
const controllerChangeEvents =
<Observable<any>>(obs_fromEvent(serviceWorker, 'controllerchange'));
@ -176,4 +176,6 @@ export class NgswCommChannel {
}));
return op_toPromise.call(mapErrorAndValue);
}
get isEnabled(): boolean { return !!this.serviceWorker; }
}