/
respondable.js
264 lines (237 loc) · 7.24 KB
/
respondable.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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
import { v1 as uuid } from './uuid';
import cache from '../base/cache';
const messages = {};
const subscribers = {};
const errorTypes = Object.freeze([
'EvalError',
'RangeError',
'ReferenceError',
'SyntaxError',
'TypeError',
'URIError'
]);
/**
* get the unique string to be used to identify our instance of axe
* @private
*/
function _getSource() {
var application = 'axeAPI',
version = '',
src;
// TODO: es-modules_audit
if (typeof axe !== 'undefined' && axe._audit && axe._audit.application) {
application = axe._audit.application;
}
if (typeof axe !== 'undefined') {
// TODO: es-modules-version
version = axe.version;
}
src = application + '.' + version;
return src;
}
/**
* Verify the received message is from the "respondable" module
* @private
* @param {Object} postedMessage The message received via postMessage
* @return {Boolean} `true` if the message is verified from respondable
*/
function verify(postedMessage) {
if (
// Check incoming message is valid
typeof postedMessage === 'object' &&
typeof postedMessage.uuid === 'string' &&
postedMessage._respondable === true
) {
var messageSource = _getSource();
return (
// Check the version matches
postedMessage._source === messageSource
);
}
return false;
}
/**
* Posts the message to correct frame.
* This abstraction necessary because IE9 & 10 do not support posting Objects; only strings
* @private
* @param {Window} win The `window` to post the message to
* @param {String} topic The topic of the message
* @param {Object} message The message content
* @param {String} uuid The UUID, or pseudo-unique ID of the message
* @param {Boolean} keepalive Whether to allow multiple responses - default is false
* @param {Function} callback The function to invoke when/if the message is responded to
*/
function post(win, topic, message, uuid, keepalive, callback) {
var error;
if (message instanceof Error) {
error = {
name: message.name,
message: message.message,
stack: message.stack
};
message = undefined;
}
var data = {
uuid: uuid,
topic: topic,
message: message,
error: error,
_respondable: true,
_source: _getSource(),
// TODO: es-modules_uuid
_axeuuid: axe._uuid,
_keepalive: keepalive
};
var axeRespondables = cache.get('axeRespondables');
if (!axeRespondables) {
axeRespondables = {};
cache.set('axeRespondables', axeRespondables);
}
axeRespondables[uuid] = true;
if (typeof callback === 'function') {
messages[uuid] = callback;
}
win.postMessage(JSON.stringify(data), '*');
}
/**
* Post a message to a window who may or may not respond to it.
* @param {Window} win The window to post the message to
* @param {String} topic The topic of the message
* @param {Object} message The message content
* @param {Boolean} keepalive Whether to allow multiple responses - default is false
* @param {Function} callback The function to invoke when/if the message is responded to
*/
function respondable(win, topic, message, keepalive, callback) {
var id = uuid();
post(win, topic, message, id, keepalive, callback);
}
/**
* Subscribe to messages sent via the `respondable` module.
*
* Axe._load uses this to listen for messages from other frames
*
* @param {String} topic The topic to listen to
* @param {Function} callback The function to invoke when a message is received
*/
respondable.subscribe = function subscribe(topic, callback) {
subscribers[topic] = callback;
};
/**
* checks if the current context is inside a frame
* @return {Boolean}
*/
respondable.isInFrame = function isInFrame(win) {
win = win || window;
return !!win.frameElement;
};
/**
* Helper closure to create a function that may be used to respond to a message
* @private
* @param {Window} source The window from which the message originated
* @param {String} topic The topic of the message
* @param {String} uuid The "unique" ID of the original message
* @return {Function} A function that may be invoked to respond to the message
*/
function createResponder(source, topic, uuid) {
return (message, keepalive, callback) => {
post(source, topic, message, uuid, keepalive, callback);
};
}
/**
* Publishes the "respondable" message to the appropriate subscriber
* @private
* @param {Window} source The window from which the message originated
* @param {Object} data The data sent with the message
* @param {Boolean} keepalive Whether to allow multiple responses - default is false
*/
function publish(source, data, keepalive) {
var topic = data.topic;
var subscriber = subscribers[topic];
if (subscriber) {
var responder = createResponder(source, null, data.uuid);
subscriber(data.message, keepalive, responder);
}
}
// added for testing so we can fire subscriber events without having
// to mock the universe going through `respondable()`
respondable._publish = publish;
/**
* Convert a javascript Error into something that can be stringified
* @param {Error} error Any type of error
* @return {Object} Processable object
*/
function buildErrorObject(error) {
var msg = error.message || 'Unknown error occurred';
var errorName = errorTypes.includes(error.name) ? error.name : 'Error';
var ErrConstructor = window[errorName] || Error;
if (error.stack) {
msg += '\n' + error.stack.replace(error.message, '');
}
return new ErrConstructor(msg);
}
/**
* Parse the received message for processing
* @param {string} dataString Message received
* @return {object} Object to be used for pub/sub
*/
function parseMessage(dataString) {
/*eslint no-empty: 0*/
var data;
if (typeof dataString !== 'string') {
return;
}
try {
data = JSON.parse(dataString);
} catch (ex) {}
if (!verify(data)) {
return;
}
if (typeof data.error === 'object') {
data.error = buildErrorObject(data.error);
} else {
data.error = undefined;
}
return data;
}
if (typeof window.addEventListener === 'function') {
window.addEventListener(
'message',
e => {
var data = parseMessage(e.data);
if (!data || !data._axeuuid) {
return;
}
var uuid = data.uuid;
/**
* NOTE: messages from other contexts (frames) in response
* to a message should not contain the same axe._uuid. We
* ignore these messages to prevent rogue postMessage
* handlers reflecting our messages.
* @see https://github.com/dequelabs/axe-core/issues/1754
*/
var axeRespondables = cache.get('axeRespondables') || {};
if (axeRespondables[uuid] && data._axeuuid === axe._uuid) {
return;
}
var keepalive = data._keepalive;
var callback = messages[uuid];
if (callback) {
var result = data.error || data.message;
var responder = createResponder(e.source, data.topic, uuid);
callback(result, keepalive, responder);
if (!keepalive) {
delete messages[uuid];
}
}
if (!data.error) {
try {
publish(e.source, data, keepalive);
} catch (err) {
post(e.source, null, err, uuid, false);
}
}
},
false
);
}
export default respondable;