-
Notifications
You must be signed in to change notification settings - Fork 263
/
Copy pathpostmessage.js
executable file
·108 lines (92 loc) · 2.72 KB
/
postmessage.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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
/**
* @module lib/postmessage
*/
import { getCallbacks, removeCallback, shiftCallbacks } from './callbacks';
/**
* Parse a message received from postMessage.
*
* @param {*} data The data received from postMessage.
* @return {object}
*/
export function parseMessageData(data) {
if (typeof data === 'string') {
try {
data = JSON.parse(data);
}
catch (error) {
// If the message cannot be parsed, throw the error as a warning
console.warn(error);
return {};
}
}
return data;
}
/**
* Post a message to the specified target.
*
* @param {Player} player The player object to use.
* @param {string} method The API method to call.
* @param {object} params The parameters to send to the player.
* @return {void}
*/
export function postMessage(player, method, params) {
if (!player.element.contentWindow || !player.element.contentWindow.postMessage) {
return;
}
let message = {
method
};
if (params !== undefined) {
message.value = params;
}
// IE 8 and 9 do not support passing messages, so stringify them
const ieVersion = parseFloat(navigator.userAgent.toLowerCase().replace(/^.*msie (\d+).*$/, '$1'));
if (ieVersion >= 8 && ieVersion < 10) {
message = JSON.stringify(message);
}
player.element.contentWindow.postMessage(message, player.origin);
}
/**
* Parse the data received from a message event.
*
* @param {Player} player The player that received the message.
* @param {(Object|string)} data The message data. Strings will be parsed into JSON.
* @return {void}
*/
export function processData(player, data) {
data = parseMessageData(data);
let callbacks = [];
let param;
if (data.event) {
if (data.event === 'error') {
const promises = getCallbacks(player, data.data.method);
promises.forEach((promise) => {
const error = new Error(data.data.message);
error.name = data.data.name;
promise.reject(error);
removeCallback(player, data.data.method, promise);
});
}
callbacks = getCallbacks(player, `event:${data.event}`);
param = data.data;
}
else if (data.method) {
const callback = shiftCallbacks(player, data.method);
if (callback) {
callbacks.push(callback);
param = data.value;
}
}
callbacks.forEach((callback) => {
try {
if (typeof callback === 'function') {
callback.call(player, param);
return;
}
callback.resolve(param);
}
catch (e) {
// empty
}
});
}