Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

webview与H5通信 #53

Open
wuyunqiang opened this issue May 24, 2018 · 0 comments
Open

webview与H5通信 #53

wuyunqiang opened this issue May 24, 2018 · 0 comments
Labels

Comments

@wuyunqiang
Copy link
Owner

wuyunqiang commented May 24, 2018

完成例子:
https://github.com/wuyunqiang/RNApp
rn端:

    //接收来自H5的消息
    onMessage = (e)=>{
        Log('WebView onMessage 收到H5参数:',e.nativeEvent.data);
        let params = e.nativeEvent.data;
        params = JSON.parse(params);
        Log('WebView onMessage 收到H5参数 json后:',params);
    };

   onLoadEnd =(e)=>{
        Log('WebView onLoadEnd e:',e.nativeEvent);
        let data = {
            source:'from rn',
        };
        this.web&&this.web.postMessage(JSON.stringify(data));//发送消息到H5
    };
          <WebView
                ref={(webview) => {
                    this.web = webview
                }}
                style={{width: '100%', height: '100%', justifyContent: 'center', alignItems: 'center'}}
                source={require('../data/testwebview.html')}
                onLoadEnd={this.onLoadEnd}//加载成功或者失败都会回调
                onMessage={this.onMessage}
                javaScriptEnabled={true}//指定WebView中是否启用JavaScript
                startInLoadingState={true} //强制WebView在第一次加载时先显示loading视图
                renderError={(e) => {
                    return <View/>;
                }}
            />

H5端:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>text webview</title>
    <script type="application/javascript">
        //相互通信只能传递字符串类型
        function clicktorn() { //发送消息到rn
            let params = {
               msg:'h5 to rn',
                source:'H5',
            };
            window.postMessage(JSON.stringify(params));//发送消息到rn
        }

        window.document.addEventListener('message', function(e) {//注册事件 接收数据
            const message = e.data;//字符串类型
            console.log('WebView message:',message);
            window.postMessage(message);
        })
    </script>
    <style type="text/css">
        body{
            margin:0;
            padding:0;
            background: #ccc;
        }
        h1{
            padding:45px;
            margin:0;
            text-align: center;
            color:#0000ff;
        }
    </style>
</head>
<body>
<h1>wuyunqiang</h1>
<button onclick=clicktorn()>单击</button>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant