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 // The "onsync" event currently understands commands (passed as
6 // registration tags) coming from the test. Any other tag is
7 // passed through to the document unchanged.
9 // "delay" - Delays finishing the sync event with event.waitUntil.
10 // Send a postMessage of "completeDelayedOneShot" to finish the
12 // "unregister" - Unregisters the sync registration from within the sync event.
16 var resolveCallback = null;
17 var rejectCallback = null;
19 this.onmessage = function(event) {
20 if (event.data['action'] === 'completeDelayedOneShot') {
21 if (resolveCallback === null) {
22 sendMessageToClients('sync', 'error - resolveCallback is null');
27 sendMessageToClients('sync', 'ok - delay completed');
31 if (event.data['action'] === 'rejectDelayedOneShot') {
32 if (rejectCallback === null) {
33 sendMessageToClients('sync', 'error - rejectCallback is null');
38 sendMessageToClients('sync', 'ok - delay rejected');
41 if (event.data['action'] === 'notifyWhenDone') {
42 var tag = event.data['tag'];
43 registration.sync.getRegistration(tag)
44 .then(function (syncRegistration) {
45 sendMessageToClients('sync', 'ok - ' + tag + ' done');
46 return syncRegistration.done;
48 .then(function(success) {
49 sendMessageToClients('sync', tag + " done result: " + success);
51 sendMessageToClients('sync', tag + " done result: error");
53 .catch(sendSyncErrorToClients);
57 this.onsync = function(event) {
58 var eventProperties = [
59 // Extract name from toString result: "[object <Class>]"
60 Object.prototype.toString.call(event).match(/\s([a-zA-Z]+)/)[1],
61 (typeof event.waitUntil)
64 if (eventProperties[0] != 'SyncEvent') {
65 sendMessageToClients('sync', 'error - wrong event type');
69 if (eventProperties[1] != 'function') {
70 sendMessageToClients('sync', 'error - wrong wait until type');
73 if (event.registration === undefined) {
74 sendMessageToClients('sync', 'error - event missing registration');
78 if (event.registration.tag === undefined) {
79 sendMessageToClients('sync', 'error - registration missing tag');
83 var tag = event.registration.tag;
85 if (tag === 'delay') {
86 var syncPromise = new Promise(function(resolve, reject) {
87 resolveCallback = resolve;
88 rejectCallback = reject;
90 event.waitUntil(syncPromise);
94 if (tag === 'unregister') {
95 event.waitUntil(event.registration.unregister()
97 sendMessageToClients('sync', 'ok - unregister completed');
102 sendMessageToClients('sync', tag + ' fired');
105 function sendMessageToClients(type, data) {
106 clients.matchAll().then(function(clients) {
107 clients.forEach(function(client) {
108 client.postMessage({type, data});
115 function sendSyncErrorToClients(error) {
116 sendMessageToClients('sync', error.name + ' - ' + error.message);