Skip to content

Instantly share code, notes, and snippets.

@saitbnzl
Last active June 24, 2019 16:33
Show Gist options
  • Save saitbnzl/b3117cb3a82505a0c84574e2e0be82e3 to your computer and use it in GitHub Desktop.
Save saitbnzl/b3117cb3a82505a0c84574e2e0be82e3 to your computer and use it in GitHub Desktop.
Auto height WebView for React Native
import {
Dimensions,
View,
WebView,
} from 'react-native';
import React, { Component } from 'react';
const injectedScript = function() {
function waitForBridge() {
if (window.postMessage.length !== 1){
setTimeout(waitForBridge, 600);
}
else {
let height = 0;
if(document.documentElement.clientHeight>document.body.clientHeight)
{
height = document.documentElement.clientHeight
}
else
{
height = document.body.clientHeight
}
window.postMessage(height);
window.postMessage = window.originalPostMessage || window.postMessage;
}
}
waitForBridge();
};
export default class SmartWebView extends Component {
state = {
webViewHeight: Number
};
static defaultProps = {
autoHeight: true,
}
constructor (props) {
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();
}
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) + ')();'}
scrollEnabled={this.props.scrollEnabled || false}
onMessage={this._onMessage}
javaScriptEnabled={true}
startInLoadingState={this.props.startInLoadingState}
automaticallyAdjustContentInsets={false}
{...this.props}
style={{width: _w-10, height: _h, backgroundColor: 'transparent'}}
/>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment