forked from scazzy/react-native-webview-autoheight
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
91 lines (81 loc) · 1.99 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
/**
* 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,
} from 'react-native';
const injectedScript = function() {
function waitForBridge() {
if (window.postMessage.length !== 1){
setTimeout(waitForBridge, 200);
}
else {
let height = 0;
if(document.documentElement.clientHeight>document.body.clientHeight)
{
height = document.documentElement.clientHeight
}
else
{
height = document.body.clientHeight
}
postMessage(height)
}
}
waitForBridge();
};
export default class MyWebView extends Component {
state = {
webViewHeight: Number
};
static defaultProps = {
autoHeight: true,
}
constructor (props: Object) {
super(props);
this.state = {
webViewHeight: this.props.defaultHeight
}
this._onMessage = this._onMessage.bind(this);
}
_onMessage(e) {
this.setState({
webViewHeight: parseInt(e.nativeEvent.data)
});
}
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;
return (
<WebView
ref={(ref) => { this.webview = ref; }}
injectedJavaScript={'(' + String(injectedScript) + ')();' +
'window.postMessage = String(Object.hasOwnProperty).replace(\'hasOwnProperty\', \'postMessage\');'}
scrollEnabled={this.props.scrollEnabled || false}
onMessage={this._onMessage}
javaScriptEnabled={true}
automaticallyAdjustContentInsets={true}
{...this.props}
style={[{width: _w}, this.props.style, {height: _h}]}
/>
)
}
}