-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcomms.js
More file actions
45 lines (43 loc) · 1.48 KB
/
comms.js
File metadata and controls
45 lines (43 loc) · 1.48 KB
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
const MuffinComms = {
_callbacks: [],
_webkitMessage: function(id, message) {
MuffinComms._callbacks[id](message);
},
isAvailable: function() {
return window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.muffinComms;
},
verifyAvailable: function() {
if (!MuffinComms.isAvailable()) {
throw "[MuffinComms] Could not complete the requested operation as the webkit service is not available";
}
},
send: function(message, data, responseType="text") {
MuffinComms.verifyAvailable();
if (message === undefined) {
throw "[MuffinComms] Message is undefined!";
}
if (data === undefined) {
data = null;
}
return new Promise(function(resolve) {
let id = MuffinComms._callbacks.push(function(data) {
if (responseType == "text") {
resolve(data);
} else if (responseType == "json") {
resolve(JSON.parse(data));
} else if (responseType == "arraybuffer") {
const length = data.length;
const buffer = new ArrayBuffer(length);
const view = new Uint8Array(buffer);
for (let i = 0; i < length; i++) {
view[i] = data.charCodeAt(i);
}
resolve(buffer);
} else {
console.error(`[MuffinComms] Unsupported responseType '${responseType}'`);
}
}) - 1;
window.webkit.messageHandlers.muffinComms.postMessage(JSON.stringify({message: message, data: data, id: id}));
});
},
};