forked from maksha/react-native-webhtmlview
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebview.android.js
98 lines (87 loc) · 2.71 KB
/
webview.android.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
96
97
98
import React, { Component } from 'react'
import { Linking, WebView } from 'react-native'
class WebHtmlView extends Component {
constructor(props) {
super(props);
this.state = {
height: props.height || 200
}
}
_handleOnMessage(event) {
const data = event.nativeEvent.data;
const height = Number(data) || props.height || 200;
console.log({ height })
if (this.state.height !== height)
this.setState({ height });
}
onShouldStartLoadWithRequest(event) {
if (event.url.search('about:blank') !== -1) {
return true
} else {
Linking.openURL(event.url)
return false
}
}
render() {
let {source, autoHeight, style, innerCSS, disablePinchZoom} = this.props;
if (!source) {
return null
}
const injectScript = `
<script>;
(function() {
var wrapper = document.createElement("div");
wrapper.id = "height-wrapper";
while (document.body.firstChild) {
wrapper.appendChild(document.body.firstChild);
}
document.body.appendChild(wrapper);
function updateHeight() {
window.__REACT_WEB_VIEW_BRIDGE.postMessage(wrapper.clientHeight);
}
updateHeight();
window.addEventListener("load", function() {
updateHeight();
window.setTimeout(updateHeight, 1000);
});
window.addEventListener("resize", updateHeight);
}());
</script>
`
const startHtmlDoc = `
<html><head>
<meta name="viewport" content="width=device-width, initial-scale=1.0${disablePinchZoom ? ', maximum-scale=1.0, user-scalable=no' : ''}">
<style>${innerCSS}</style></head><body>
`
const endHtmlDoc = '</body></html>'
if (source.html && autoHeight) {
let finalHtmlDoc = startHtmlDoc +
'<div style="word-break:break-word">' +
source.html +
'</div>' +
injectScript +
endHtmlDoc
source = Object.assign({}, source, {
html: finalHtmlDoc
})
}
return (
<WebView
source={source}
style={[style, autoHeight ? {height: this.state.height + 25} : null]}
automaticallyAdjustContentInsets={false}
scrollEnabled={!autoHeight}
javaScriptEnabled={autoHeight}
showsVerticalScrollIndicator={false}
showsHorizontalScrollIndicator={false}
onShouldStartLoadWithRequest={this.onShouldStartLoadWithRequest}
onMessage={this._handleOnMessage.bind(this)} />
)
}
}
WebHtmlView.defaultProps = {
innerCSS: '',
autoHeight: true,
disablePinchZoom: false,
};
export default WebHtmlView