1

I'm basically asking the same question as this one, but for RN 0.28+. The solutions presented in the various answers do not seem to work in RN 0.28, so I'm hoping there are other configurations or hacks...

Is there any way to resize a WebView based on the height of its content? I've tried injecting the document height into the title and reading that back with onNavigationStateChange, but it always returns 568 (similar to the comments to this gist).

 return <TouchableHighlight onPress={() => console.log('touched ' + this.props.choice.id)}
                           style={styles.choiceRowWrapper} >
      <View style={styles.choiceWebViewWrapper}>
        <WebView automaticallyAdjustContentInsets={false}
                 javascriptEnabled={true}
                 onNavigationStateChange={(navState) => this._updateWebViewNavState(navState)}
                 scrollEnabled={false}
                 source={{html: WrapHTML(this.props.choice.text)}}
                 style={[styles.choiceWebView, {height: this.state.height}]} />
    </View>
  </TouchableHighlight>
 }
  _updateWebViewNavState = (navState) => {
    console.log(navState);
    if (navState.title) {
      this.setState({ height: parseInt(navState.title) });
    }
  }

function WrapHTML (markup) {
    return `<!DOCTYPE html>
      <html>
        <head>
        </head>
        <body class="content">
          ${markup}
        </body>
        <script>window.location.hash = 1;document.title = document.height;</script>
      </html>`;
  };

I have also tried various things inside of the WebView document, like:

document.scrollHeight.contentSize.height
document.body.height

But all of them are undefined. The closest I got was something like this (from this iOS SO question):

document.getElementById("content").offsetHeight;

But for short text content that returns 20, and for a longer text content (one full sentence) it returns 40...neither of which seems accurate.

I also started trying this RN component, but the repo indicates that it is not being actively maintained -- the latest version on npm doesn't support RN 0.28 because of the change they made for importing React by itself (instead of from ReactNative).

Has anyone gotten WebViews to resize properly with RN 0.28?

Community
  • 1
  • 1
user
  • 4,651
  • 5
  • 32
  • 60

1 Answers1

0

After a lot of research and tinkering, I found this approach which is a slightly more involved version of setting the document title to the screen height value. In my tests, this has worked on both Android and iOS with react native 0.47.

https://gist.github.com/xyos/dcaa43fa561760b9d6194d78e5fb7721

Lorenz
  • 737
  • 1
  • 7
  • 26