This repository has been archived by the owner on May 18, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
pushMessaging.js
85 lines (75 loc) · 2.61 KB
/
pushMessaging.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
var Event = require('cordova-plugin-chrome-apps-common.events');
var exec = require('cordova/exec');
var channel = require('cordova/channel');
var helpers = require('cordova-plugin-chrome-apps-common.helpers');
var eventsToFireOnStartUp = [];
exports.getChannelId = function(interactive, callback) {
var outstandingCallbacks = 2;
var result = {};
checkToIssueCallback = function() {
outstandingCallbacks--;
if (outstandingCallbacks === 0) {
callback(result);
}
};
chrome.identity.getAuthToken({interactive:true}, function(token) {
var channelApiUrl = 'https://www.googleapis.com/gcm_for_chrome/v1/channels/id';
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4) {
if (req.status == 200) {
var response = JSON.parse(req.responseText);
result['channelId'] = response.id + '/' + chrome.runtime.id;
} else {
console.error('Error sending channel ID request, server returned with status ' + req.status);
}
checkToIssueCallback();
}
};
req.open('GET', channelApiUrl + '?access_token=' + token, true);
req.send(null);
});
var win = function(registrationId) {
if(require('cordova/platform').id == "ios"){
result['deviceToken'] = registrationId;
} else {
result['registrationId'] = registrationId;
}
checkToIssueCallback();
};
exec(win, checkToIssueCallback, 'ChromePushMessaging', 'getRegistrationId', [ chrome.runtime.getManifest().senderId ]);
};
exports.onMessage = new Event('onMessage');
function firePendingEvents() {
var msg;
while (msg = eventsToFireOnStartUp.shift()) {
processMessage(msg);
}
eventsToFireOnStartUp = null;
}
function onMessageFromNative(msg) {
if (eventsToFireOnStartUp) {
eventsToFireOnStartUp.push(msg);
} else {
processMessage(msg);
}
}
function processMessage(msg) {
exports.onMessage.fire(msg);
}
channel.createSticky('onChromePushMessagingReady');
channel.waitForInitialization('onChromePushMessagingReady');
channel.onCordovaReady.subscribe(function() {
exec(onMessageFromNative, undefined, 'ChromePushMessaging', 'messageChannel', []);
helpers.runAtStartUp(function() {
if (eventsToFireOnStartUp.length) {
helpers.queueLifeCycleEvent(firePendingEvents);
} else {
eventsToFireOnStartUp = null;
}
});
channel.initializationComplete('onChromePushMessagingReady');
});