React Native - webview 内外通信

React Native - webview 内外通信

消息的传递需要注意是字符串.

webview 向 RN 发送消息

js 发送消息:

if (window.ReactNativeWebView) {
    ReactNativeWebView.postMessage("123321");
}

RN 收消息:

<WebView
    ref={webView}
    originWhitelist={['*']}
    javaScriptEnabled={true}
    domStorageEnabled={true}
    onMessage={event => {
        const {data} = event.nativeEvent;
        console.log('message from the WebView: ', data);
    }}
    ...
    />

RN 向 webview 注入 js

可以在 RN 向 webview 注入 js 达到向 webview 里的页面进行通信

webView.current.postMessage(data);

webview 接收消息:

这里有两点需要注意:

  1. 是 document 上的监听事件, 不是 window
  2. 如果直接打印 event, 得到的是 {"isTrusted": false}, 而使用 event.data 却可以正常的获取数据
document.addEventListener("message", (event) => {
    alert(JSON.stringify(event.data));
});

demo

RN App.js

import React, {createRef} from 'react';
import {Button, SafeAreaView, StyleSheet, View} from 'react-native';
import WebView from 'react-native-webview';

const App = () => {
    const webView = createRef();

    return (
        <SafeAreaView>
            <View style={{height: 500}}>
                <Button
                    title="update time"
                    onPress={() => {
                        const injected = webView.current.postMessage(JSON.stringify({a: '123', b: '456'}));
                    }}
                />
                <WebView
                    ref={webView}
                    originWhitelist={['*']}
                    javaScriptEnabled={true}
                    domStorageEnabled={true}
                    onMessage={event => {
                        const {data} = event.nativeEvent;
                        console.log('String message from the WebView: ', data);
                    }}
                    source={{uri: 'http://192.168.11.228:3000/test.html'}}
                />
            </View>
        </SafeAreaView>
    );
};

const styles = StyleSheet.create({});

export default App;
DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Documenttitle>
        <script>
            document.addEventListener("message", (event) => {
                alert(JSON.stringify(event.data));
            });

            function send() {
                if (window.ReactNativeWebView) {
                    ReactNativeWebView.postMessage("123321");
                }
            }
        script>
    head>
    <body>
        <a onclick="send()">senda>
        <p id="time">timep>
    body>
html>

你可能感兴趣的:(React,react,native,javascript,ecmascript)