UNPKG

1.39 kBJavaScriptView Raw
1/**
2 * Provides a single useful interface for performing remote function calls
3 */
4class RemoteInterface {
5 constructor(source, origin) {
6 this._source = source;
7 this._origin = origin;
8
9 if (typeof this._source.postMessage !== 'function') {
10 throw new Error("RemoteInterface() provided source is invalid");
11 }
12 }
13
14 get source() {
15 return this._source;
16 }
17
18 get origin() {
19 return this._origin;
20 }
21
22 /**
23 * Returns the frameElement ID, or undefined if no frameElement exists in the source
24 */
25 get id() {
26 return this.source.frameElement ? this.source.frameElement.id : undefined;
27 }
28
29 /**
30 * Use the registered source to send data upstream/downstream
31 */
32 send(event, data) {
33 const sendData = {
34 event: event,
35 data: (data || {})
36 };
37
38 this.source.postMessage(JSON.stringify(sendData), this.origin);
39 }
40
41 /**
42 * Creates and returns a default RemoteInterface for the parent stack
43 */
44 static default() {
45 const parentStack = window.parent ? ((window.frameElement && window.frameElement.nodeName == "IFRAME") ? window.parent : undefined) : undefined;
46
47 if (parentStack) {
48 return new RemoteInterface(parentStack, "*");
49 }
50
51 return undefined;
52 }
53}
54
55module.exports = RemoteInterface;
\No newline at end of file