This repository has been archived by the owner on Oct 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.ts
98 lines (80 loc) · 2.68 KB
/
index.ts
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
import { Observer } from '../../common/utils';
import { Logger } from '../../common/utils/logger';
import { Message, MessageBridgeOptions } from './types';
export class MessageBridge {
private logger: Logger;
private allowedOrigins: string;
private contentWindow: Window;
private domains: Array<string>;
private observers: Record<string, Observer> = {};
private sourceBlockList: Array<string> = ['vue-devtools-proxy', 'vue-devtools-backend'];
private originBlockList: Array<string> = ['https://sketchfab.com'];
constructor(options: MessageBridgeOptions) {
const {
contentWindow,
domains = [],
allowedOrigins = '*',
sourceBlockList = [],
logger,
} = options;
this.logger = logger;
this.domains = domains;
this.allowedOrigins = allowedOrigins;
this.sourceBlockList.push(...sourceBlockList);
if (typeof window === 'undefined') {
throw new Error('MessageBridge: window is undefined');
}
this.contentWindow = contentWindow;
window.addEventListener('message', this.onReceiveMessage);
}
publish = (type: Message, message: Object = {}) => {
this.logger.log('MessageBridge', 'Posting message to frame', type, message);
this.contentWindow.postMessage(
{
type,
data: message,
},
this.allowedOrigins,
);
};
listen = (type: Message, listener: Function) => {
if (!this.observers[type]) {
this.observers[type] = new Observer({ logger: this.logger });
}
this.observers[type].subscribe(listener);
};
destroy() {
Object.entries(this.observers).forEach(([type, observer]) => {
observer.reset();
delete this.observers[type];
});
window.removeEventListener('message', this.onReceiveMessage);
delete this.logger;
delete this.allowedOrigins;
delete this.contentWindow;
delete this.domains;
delete this.observers;
delete this.sourceBlockList;
}
private onReceiveMessage = (event: MessageEvent) => {
const { type, data, source } = event.data;
if (this.sourceBlockList.includes(source) || this.originBlockList.includes(event.origin)) {
return;
}
const hasType = !!type;
const isFromAllowedOrgin = !this.domains.length || this.domains.includes(event.origin);
const hasListenerRegistered = this.observers.hasOwnProperty(type);
this.logger.log(
'MessageBridge',
`Message received -
TYPE: ${event.type}
ORIGIN: ${event.origin}
DATA: ${JSON.stringify(event.data)} `,
);
if (!hasType || !isFromAllowedOrgin || !hasListenerRegistered) {
this.logger.log('MessageBridge', 'Message discarded');
return;
}
this.observers[type].publish(data);
};
}