-
Notifications
You must be signed in to change notification settings - Fork 1
/
ReactNativeMessenger.js
47 lines (39 loc) · 1.22 KB
/
ReactNativeMessenger.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
import IMessenger from "~/shared/messaging/IMessenger";
import * as Message from "~/shared/messaging/Message";
export default class ReactNativeMessenger extends IMessenger {
constructor() {
super();
this._webView = null;
this._initialised = false;
}
init(webView) {
if (this._initialised) return;
this._webView = webView;
this._webView.onMessage = this._onMessage.bind(this);
this._initialised = true;
}
_postMessage(data) {
if (this._webView === null) return;
const script = `
(function() {
window.dispatchEvent(new MessageEvent('message', {data: ${data}}));
})()
`;
this._webView.injectJavaScript(script);
}
_onMessage(event) {
const message = this._translateMessage(event);
console.log("message received from webview");
console.log(message);
if (message.type === "connected") {
this._setConnected();
}
this._emit(message.type, message.data);
}
_translateMessage(event) {
if (event.nativeEvent) {
return Message.parse(event.nativeEvent.data);
}
return Message("");
}
}