美文网首页React Native学习
react-native webview 与js通信

react-native webview 与js通信

作者: 我的昵称好听吗 | 来源:发表于2018-05-08 15:49 被阅读81次

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

先上图,点击webview中的按钮,获取到html页面中postMessage的数据

image.png

使用:

1.rn端

  • 添加onMessage 属性
onMessage = (event) => {
    //webview中的html页面传过来的的数据在event.nativeEvent.data上
    console.log(event.nativeEvent.data);
}

<WebView onMessage={this.onMessage} source={{ uri: url }}/>

2.html(js)端

  • window.postMessage
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
    </head>

    <body>
        <button id="btn">点击我</button>
    </body>
    <script>
        function test() {
            console.log('只能传递一个字符串类型的参数');

            if(!!window.postMessage) {
                window.postMessage('只能传递一个字符串类型的参数');
            }
        }

        document.getElementById("btn").onclick = function() {
            test();
        }
    </script>

</html>

相关文章

网友评论

    本文标题:react-native webview 与js通信

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