-
Notifications
You must be signed in to change notification settings - Fork 1
/
BridgedWebView.js
81 lines (68 loc) · 2.03 KB
/
BridgedWebView.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
import React, { Component } from "react";
import { WebView } from "react-native-webview";
import ReactNativeBridge from "./ReactNativeBridge";
import WebViewBridge from "./WebViewBridge";
export default class BridgedWebView extends Component {
constructor(props) {
super(props);
const { ref } = props;
this.WebView = ref || React.createRef();
}
injectReactNativeBridge = () => {
// Inject the ReactNativeBridge into the WebView
this.WebView.current.injectJavaScript(
"(" + ReactNativeBridge.toString() + "())"
);
};
// Handles incoming messages from the WebView and calls a function
// which should have been defined using one of the addFunction methods
handle = message => {
try {
const { id, functionName, args } = JSON.parse(message);
// Retrieve the function from the functions object
const func = WebViewBridge.functions[functionName];
// Call the function and pass the result to the callback
func(args, (err, res) => {
this.respond({
id,
err,
res
});
});
} catch (err) {
console.log(err);
this.respond({
err
});
}
};
respond = message => {
// After processing the requested function, WebViewBridge responds to the WebView
this.WebView.current.injectJavaScript(`
ReactNativeBridge.response(${JSON.stringify(message)});
`);
};
render() {
const { ref, onMessage, onLoad, ...props } = this.props;
return (
<WebView
ref={this.WebView}
// When ReactNativeBrige calls a function we handle it here
// ReactNativeBridge.call => _ReactNativeBridge.postMessage => onMessage => WebViewBridge.handle
onLoad={event => {
this.injectReactNativeBridge();
if (onLoad) {
onLoad(event);
}
}}
onMessage={event => {
this.handle(event.nativeEvent.data);
if (onMessage) {
onMessage(event);
}
}}
{...props}
/>
);
}
}