OLD | NEW |
(Empty) | |
| 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. |
| 4 |
| 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. |
| 12 if (registration) |
| 13 return registration.unregister(); |
| 14 }).then(function() { |
| 15 // Register the Service Worker again. |
| 16 return navigator.serviceWorker.register(script, { scope: scope }); |
| 17 }).then(function(registration) { |
| 18 if (registration.active) { |
| 19 return registration; |
| 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); |
| 26 }); |
| 27 }); |
| 28 } else { |
| 29 return Promise.reject('Service Worker in invalid state.'); |
| 30 } |
| 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); |
| 37 }); |
| 38 |
| 39 registration.active.postMessage(channel.port2, |
| 40 [ channel.port2 ]); |
| 41 |
| 42 messagePort = channel.port1; |
| 43 messagePort.start(); |
| 44 }); |
| 45 }); |
| 46 } |
OLD | NEW |