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 // Returns a promise that will be resolved with an activated Service
6 // Worker, or rejects when the Service Worker could not be started. There
7 // will be a message port to and from the worker in |messagePort|.
8 function GetActivatedServiceWorker(script
, scope
) {
9 return navigator
.serviceWorker
.getRegistration(scope
)
10 .then(function(registration
) {
11 // Unregister any existing Service Worker.
13 return registration
.unregister();
15 // Register the Service Worker again.
16 return navigator
.serviceWorker
.register(script
, { scope
: scope
});
17 }).then(function(registration
) {
18 if (registration
.active
) {
20 } else if (registration
.waiting
|| registration
.installing
) {
21 var worker
= registration
.waiting
|| registration
.installing
;
22 return new Promise(function(resolve
) {
23 worker
.addEventListener('statechange', function () {
24 if (worker
.state
=== 'activated')
25 resolve(registration
);
29 return Promise
.reject('Service Worker in invalid state.');
31 }).then(function(registration
) {
32 return new Promise(function(resolve
) {
33 var channel
= new MessageChannel();
34 channel
.port1
.addEventListener('message', function(event
) {
35 if (event
.data
== 'ready')
36 resolve(registration
);
39 registration
.active
.postMessage(channel
.port2
,
42 messagePort
= channel
.port1
;