forked from angular/angular
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathiframe-message-bus.ts
More file actions
75 lines (68 loc) · 2.28 KB
/
iframe-message-bus.ts
File metadata and controls
75 lines (68 loc) · 2.28 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
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
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Events, MessageBus, Parameters} from '../projects/protocol';
export class IFrameMessageBus extends MessageBus<Events> {
private listeners: any[] = [];
constructor(
private readonly source: string,
private readonly destination: string,
private readonly docWindow: () => Window,
) {
super();
}
override on<E extends keyof Events>(topic: E, cb: Events[E]): () => void {
const listener = (e: MessageEvent) => {
if (!e.data || e.data.source !== this.destination || !e.data.topic) {
return;
}
if (e.data.topic === topic) {
(cb as () => void).apply(null, e.data.args);
}
};
window.addEventListener('message', listener);
this.listeners.push(listener);
return () => {
this.listeners.splice(this.listeners.indexOf(listener), 1);
window.removeEventListener('message', listener);
};
}
override once<E extends keyof Events>(topic: E, cb: Events[E]): void {
const listener = (e: MessageEvent) => {
if (!e.data || e.data.source !== this.destination || !e.data.topic) {
return;
}
if (e.data.topic === topic) {
(cb as any).apply(null, e.data.args);
window.removeEventListener('message', listener);
}
};
window.addEventListener('message', listener);
}
override emit<E extends keyof Events>(topic: E, args?: Parameters<Events[E]>): boolean {
this.docWindow().postMessage(
{
source: this.source,
topic,
args,
// Since both the devtools app and the demo app use IframeMessageBus,
// we want to only ignore the ngZone for the demo app. This will let us
// prevent infinite change detection loops triggered by message
// event listeners but also not prevent the NgZone in the devtools app
// from updating its UI.
__ignore_ng_zone__: this.source === 'angular-devtools',
__NG_DEVTOOLS_EVENT__: true,
},
'*',
);
return true;
}
override destroy(): void {
this.listeners.forEach((l) => window.removeEventListener('message', l));
this.listeners = [];
}
}