react-native WebView获取内容高度

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

injectedJavaScriptstring设置在网页加载之前注入的一段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高度,从而实现自适应。直接上代码:

importReact, { Component }from'react'import{ WebView, Dimensions, ScrollView}from'react-native'constBaseScript =`

    (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);

    } ())

    `constHTMLTEXT =`<h1>This HTML snippet is now rendered with native components !</h1>

    <img src="https://i.imgur.com/dHLmxfO.jpg?2" />`classAutoHeightWebViewextendsComponent{constructor(props) {super(props);this.state = ({height:0})  }/**

  * web端发送过来的交互消息

  */onMessage (event) {try{constaction =JSON.parse(event.nativeEvent.data)if(action.type ==='setHeight'&& action.height >0) {this.setState({height: action.height })      }    }catch(error) {// pass}  }  render () {return()  }}export default RZWebView

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容