ReactNative 与 WebView 交互

在 react native 开发中,webview 通常只是用来显示网页或者带有 html 标签的字符串。但是,很多时候需要 react native 与 webview 的内容进行交互,比如点击事件,滑动事件等等。react native 可以通过监听 onMessage 可以接收到由 window.postMessage 发送的 字符串。

案例

1)图片点击预览

通过给 标签添加点击事件,并且获取标签中图片的链接,得到整个web的图片链接数组,然后转为 json 字符串通过 window.postMessage 通知给 react native

/**
 * web端发送过来的交互消息
 * @param {*} event 
 */
onMessage(event) {
    try {
        const action = JSON.parse(event.nativeEvent.data);

        if(action.type == 'images'){
            //跳转到图片预览页面
            var pos = 0;
            for(let i = 0; i < action.images.length; i++){
                if(action.images[i] == action.url){
                    break;
                }
                pos++;
            }
            this.props.navigation.navigate('ImagePreview', {
                position: pos,
                images: action.images,
            })
        }
    } catch (error) {
        console.log(error)
    }
}
render(){
    return(
        
    )
}
2)webview 滑动到底部事件监听
/**
 * web端发送过来的交互消息
 * @param {*} event 
 */
onMessage(event) {
    try {
        const action = JSON.parse(event.nativeEvent.data);

        console.log("action:--->  "+JSON.stringify(action))

        if (action.type == 'update') {
            //滑动到底部
        }
    } catch (error) {
        console.log(error)
    }
}

render(){
    return(
         0) ? bodyScrollTop : documentScrollTop;
                        return scrollTop;
                    }
                    function getScrollHeight(){
                      var scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0;
                      if(document.body){
                        bodyScrollHeight = document.body.scrollHeight;
                      }
                      if(document.documentElement){
                        documentScrollHeight = document.documentElement.scrollHeight;
                      }
                      scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight;
                      return scrollHeight;
                    }
                    function getWindowHeight(){
                      var windowHeight = 0;
                      if(document.compatMode == "CSS1Compat"){
                        windowHeight = document.documentElement.clientHeight;
                      }else{
                        windowHeight = document.body.clientHeight;
                      }
                      return windowHeight;
                    }

                    window.onscroll = function(){
                        if(getScrollTop() + getWindowHeight() == getScrollHeight()){
                            window.postMessage(JSON.stringify({type: \'update\'}));
                        }
                    };
                }());`}
            javaScriptEnabled={true}
            onMessage={this.onMessage.bind(this)}/>
    )
}

你可能感兴趣的:(ReactNative 与 WebView 交互)