-
Notifications
You must be signed in to change notification settings - Fork 75
/
index.js
95 lines (84 loc) · 2.31 KB
/
index.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/**
* Custom WebView with autoHeight feature
*
* @prop source: Same as WebView
* @prop autoHeight: true|false
* @prop defaultHeight: 100
* @prop width: device Width
* @prop ...props
*
* @author Elton Jain
* @version v1.0.2
*/
import React, { Component } from 'react';
import {
View,
Dimensions,
WebView,
Platform,
} from 'react-native';
import PropTypes from "prop-types";
const injectedScript = function() {
function waitForBridge() {
if (window.postMessage.length !== 1){
setTimeout(waitForBridge, 200);
}
else {
postMessage(
Math.max(document.documentElement.clientHeight, document.documentElement.scrollHeight, document.body.clientHeight, document.body.scrollHeight)
)
}
}
waitForBridge();
};
export default class MyWebView extends Component {
state = {
webViewHeight: Number
};
static propTypes = {
onMessage: PropTypes.func
};
static defaultProps = {
autoHeight: true,
onMessage: () => {}
};
constructor (props: Object) {
super(props);
this.state = {
webViewHeight: this.props.defaultHeight
}
this._onMessage = this._onMessage.bind(this);
}
_onMessage(e) {
const { onMessage } = this.props;
this.setState({
webViewHeight: parseInt(e.nativeEvent.data)
});
onMessage(e);
}
stopLoading() {
this.webview.stopLoading();
}
reload() {
this.webview.reload();
}
render () {
const _w = this.props.width || Dimensions.get('window').width;
const _h = this.props.autoHeight ? this.state.webViewHeight : this.props.defaultHeight;
const androidScript = 'window.postMessage = String(Object.hasOwnProperty).replace(\'hasOwnProperty\', \'postMessage\');' +
'(' + String(injectedScript) + ')();';
const iosScript = '(' + String(injectedScript) + ')();' + 'window.postMessage = String(Object.hasOwnProperty).replace(\'hasOwnProperty\', \'postMessage\');';
return (
<WebView
ref={(ref) => { this.webview = ref; }}
injectedJavaScript={Platform.OS === 'ios' ? iosScript : androidScript}
scrollEnabled={this.props.scrollEnabled || false}
javaScriptEnabled={true}
automaticallyAdjustContentInsets={true}
{...this.props}
onMessage={this._onMessage}
style={[{ width: _w }, this.props.style, { height: _h }]}
/>
)
}
}