1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 var activatedServiceWorkerPromise = null;
7 // Returns a promise that will be resolved with an activated Service
8 // Worker, or rejects when the Service Worker could not be started. There
9 // will be a message port to and from the worker in |messagePort|.
10 function GetActivatedServiceWorker(script, scope) {
11 if (activatedServiceWorkerPromise == null) {
12 activatedServiceWorkerPromise =
13 navigator.serviceWorker.getRegistration(scope)
14 .then(function(registration) {
15 // Unregister any existing Service Worker.
17 return registration.unregister();
19 // Register the Service Worker again.
20 return navigator.serviceWorker.register(script, { scope: scope });
21 }).then(function(registration) {
22 if (registration.active) {
24 } else if (registration.waiting || registration.installing) {
25 var worker = registration.waiting || registration.installing;
26 return new Promise(function(resolve) {
27 worker.addEventListener('statechange', function () {
28 if (worker.state === 'activated')
29 resolve(registration);
33 return Promise.reject('Service Worker in invalid state.');
35 }).then(function(registration) {
36 return new Promise(function(resolve) {
37 var channel = new MessageChannel();
38 channel.port1.addEventListener('message', function(event) {
39 if (event.data == 'ready')
40 resolve(registration);
43 registration.active.postMessage(channel.port2,
46 messagePort = channel.port1;
52 return activatedServiceWorkerPromise;