React native: webview height

I just follow this guide: https://github.com/react-native-community/react-native-webview/blob/master/docs/Guide.md#communicating-between-js-and-native and succeeded in my work. Here is solution: 1. Define script to send document height to native env after loaded website. 2. Handle onMesssage of webview component and reset Height via state.

const webViewScript = `
  setTimeout(function() { 
    window.postMessage(document.documentElement.scrollHeight); 
  }, 500);
  true; // note: this is required, or you'll sometimes get silent failures
`;


...
constructor(props) {
    super(props);
    this.state = {
      webheight:100,
    }

...

<WebView style={{height: this.state.webheight}}
  automaticallyAdjustContentInsets={false}
  scrollEnabled={false}
  source={{uri: "http://<your url>"}}
  onMessage={event => {
    this.setState({webheight: parseInt(event.nativeEvent.data)});
  }}
  javaScriptEnabled={true}
  injectedJavaScript ={webViewScript}
  domStorageEnabled={true}
></WebView>

Hope that help!


I wrap WebView inside a View, and set the height from the View.

<View style={{ height: 200 }}>
  <WebView
    automaticallyAdjustContentInsets={false}
    source={{uri: 'https://player.vimeo.com/video/24156534?title=0&byline=0&portrait=0'}}
  />
</View>

A reliable implementation of this behavior is with useAutoheight hook from @formidable-webview/webshell library. The latter allows to inject "features" into WebViews, e.g. scripts and behaviors. In this example, we will use 3 features + the aforementioned hook:

  • HandleHTMLDimensionsFeature which is required by useAutoheight hook to get document size updates;
  • ForceResponsiveViewportFeature to work around mobile virtual viewport;
  • ForceElementSizeFeature to work around cyclic size constraints

This component should work with any webpage.

import React from 'react';
import makeWebshell, {
  HandleHTMLDimensionsFeature,
  ForceResponsiveViewportFeature,
  ForceElementSizeFeature,
  useAutoheight
} from '@formidable-webview/webshell';
import WebView from 'react-native-webview';

const Webshell = makeWebshell(
  WebView,
  new HandleHTMLDimensionsFeature(),
  new ForceResponsiveViewportFeature({ maxScale: 1 }),
  new ForceElementSizeFeature({
    target: 'body',
    heightValue: 'auto',
    widthValue: 'auto'
  })
);

export default function ResilientAutoheightWebView(props) {
  const { autoheightWebshellProps } = useAutoheight({
    webshellProps: props
  });
  return <Webshell {...autoheightWebshellProps} />;
}

More resources:

  • Try this on Expo
  • Full guide here.