react-native WebView获取内容高度

作者: 朱man | 来源:发表于2018-06-21 23:38 被阅读245次

    需求背景

    我们APP里有个商品详情页,页面上半部分是自己写的界面,下半部分则要展示一段由后台返回的html标签,图文混排的形式。由于WebView如果不给定一个高度,将无法展示内容,但html内容是运营人员编写的,无法固定高度。我第一反应是由于WebView没有获取内容高度的api,所以有没有好用的第三方组件呢?ps:最终方案可以直接看文章最后!

    第三方组件

    GitHub上一个高分组件,也是别人推荐的react-native-htmlview,其能渲染一段html标签的字符串而无需给定高度,官方例子:

    import React from 'react';
    import HTMLView from 'react-native-htmlview';
    
    class App extends React.Component {
      render() {
        const htmlContent = `<p><a href="http://jsdf.co">&hearts; nice job!</a></p>`;
    
        return (
          <HTMLView
            value={htmlContent}
            stylesheet={styles}
          />
        );
      }
    }
    

    但我们很快发现在安卓里img渲染不出来,在GitHub的issues里也有相应的提问,解决办法基本都是使用该组件的renderNode属性,判断是否为img标签,然后给一个固定高度

    renderNode(node, index, siblings, parent, defaultRenderer) {
        if (node.name == 'img') {
          const { src, height } = node.attribs;
          const imageHeight = height || 300;
          return (
            <Image
              key={index}
              style={{ width: width * PixelRatio.get(), height: imageHeight * PixelRatio.get() }}
              source={{ uri: src }} />
          );
        }
      }
    

    但我们的图片怎么能固定高度呢,图片不就变形了吗?最终这个方案被放弃了。

    后来我们找了另一个组件react-native-render-html,该组件使用简单点,提供了很多属性,对图片的最大宽度能用属性设置,在安卓上表现很好,图片正常显示。官方例子:

    import React, { Component } from 'react';
    import { ScrollView, Dimensions } from 'react-native';
    import HTML from 'react-native-render-html';
    
    const htmlContent = `
        <h1>This HTML snippet is now rendered with native components !</h1>
        <img src="https://i.imgur.com/dHLmxfO.jpg?2" />
    `;
    
    export default class Demo extends Component {
        render () {
            return (
                <ScrollView style={{ flex: 1 }}>
                    <HTML html={htmlContent} imagesMaxWidth={Dimensions.get('window').width} />
                </ScrollView>
            );
        }
    }
    

    但……当我们换上一张尺寸较大的图片时,ios端展示的图片模糊了,无法忍受的那种。同样GitHub的issues里也有相应的提问。有人给出了答案就是修改源码,原因是图片给了一个固定初始宽高,等图片加载完后就变成stretched了,就模糊了;解决方法就是等图片加载完后,设一个真实的宽高,这样图片就不模糊了。但这不是我心中完美的方法,并且后面发现其无法渲染span、em等标签,所以还是放弃了。

    原生组件WebView

    发现第三方组件都会有点问题,正当无奈的时候,脑子开窍了。WebView没有直接提供内容高度的属性,不代表没有间接获取内容高度的属性啊。百度一搜,各种答案,前面的那些折腾,简直愚蠢啊。

    方法一

    使用WebView的onNavigationStateChange属性。获取高度原理是当文档加载完后js获取文档高度然后添加到title标签中。这时通过监听导航状态变化的函数 onNavigationStateChange 来将title的值读取出来赋值给this.state.height从而使webview的高度做到自适应。

    constructor(props) {
        super(props);
        this.state={
          height:500,
        }
      }
    
    <View style={{height:this.state.height}}>
        <WebView
            source={{html: `<!DOCTYPE html><html><body>${htmlContent}<script>window.onload=function(){window.location.hash = 1;document.title = document.body.clientHeight;}</script></body></html>`}}
            style={{flex:1}}
            bounces={false}
            scrollEnabled={false}
            automaticallyAdjustContentInsets={true}
            contentInset={{top:0,left:0}}
            onNavigationStateChange={(title)=>{
              if(title.title != undefined) {
                this.setState({
                  height:(parseInt(title.title)+20)
                })
              }
            }}
            >
        </WebView>
    </View>
    

    但是如果我的source是一个uri呢,这种方法还是不够灵活。

    终极方法

    使用WebView的injectedJavaScriptonMessage属性。ps:在低版本的RN中无法使用onMessage属性官方解释:

    injectedJavaScript string
    
    设置在网页加载之前注入的一段JS代码。
    
    onMessage function
    
    在webview内部的网页中调用`window.postMessage`方法时可以触发此属性对应的函数,从而实现网页和RN之间的数据交换。 设置此属性的同时会在webview中注入一个`postMessage`的全局函数并覆盖可能已经存在的同名实现。
    
    网页端的`window.postMessage`只发送一个参数`data`,此参数封装在RN端的event对象中,即`event.nativeEvent.data`。`data`只能是一个字符串。
    

    思路是使用injectedJavaScript注入一段js代码获取网页内容高度,然后调用window.postMessage方法把高度回调给onMessage方法,然后setState,改变webView高度,从而实现自适应。直接上代码:

    import React, { Component } from 'react'
    import {
      WebView,
      Dimensions,
      ScrollView
    } from 'react-native'
    
    const BaseScript =
        `
        (function () {
            var height = null;
            function changeHeight() {
              if (document.body.scrollHeight != height) {
                height = document.body.scrollHeight;
                if (window.postMessage) {
                  window.postMessage(JSON.stringify({
                    type: 'setHeight',
                    height: height,
                  }))
                }
              }
            }
            setTimeout(changeHeight, 300);
        } ())
        `
    
    const HTMLTEXT = `<h1>This HTML snippet is now rendered with native components !</h1>
        <img src="https://i.imgur.com/dHLmxfO.jpg?2" />`
    
    class AutoHeightWebView extends Component {
      constructor (props) {
        super(props);
        this.state = ({
          height: 0
        })
      }
    
      /**
       * web端发送过来的交互消息
       */
      onMessage (event) {
        try {
          const action = JSON.parse(event.nativeEvent.data)
          if (action.type === 'setHeight' && action.height > 0) {
            this.setState({ height: action.height })
          }
        } catch (error) {
          // pass
        }
      }
    
      render () {
        return (
          <ScrollView>
            <WebView
              injectedJavaScript={BaseScript}
              style={{
                width: Dimensions.get('window').width,
                height: this.state.height
              }}
              automaticallyAdjustContentInsets
              source={{ html: HTMLTEXT }}// 这里可以使用uri
              decelerationRate='normal'
              scalesPageToFit
              javaScriptEnabled // 仅限Android平台。iOS平台JavaScript是默认开启的。
              domStorageEnabled // 适用于安卓
              scrollEnabled={false}
              onMessage={this.onMessage.bind(this)}
            />
          </ScrollView>
        )
      }
    }
    
    export default RZWebView
    

    这里有点小插曲,我们在BaseScript这段js字符串中,使用//写了点注释,结果安卓端onMessage方法就不被调用了。非常郁闷,最后查找资料发现这种//注释方法是会导致这段js不被执行的,正确的注释方式是/**/

    最后完美解决问题,完成需求。这中间过程艰辛,希望本文的总结能帮到大家少走冤路。谢谢!

    参考文章

    《ReactNative WebView高度自适应》
    《React-Native WebView 测量网页高度》

    相关文章

      网友评论

      • 苦海行舟:可以仿RN组件写一个webview然后增加一个返回高度的接口

      本文标题:react-native WebView获取内容高度

      本文链接:https://www.haomeiwen.com/subject/aiacyftx.html