实现带回调的通讯
Web 端实现
在网页中,我们使用 window.callbacks
对象来注册回调函数,并将 callbackId
传递给 App:
<script>
window.callbacks = {
callbacks: {},
register: function(successCallback, errorCallback) {
const callbackId = Date.now().toString();
this.callbacks[callbackId] = {
success: successCallback,
error: errorCallback,
};
return callbackId;
},
execute: function(callbackId, type, data) {
const callback = this.callbacks[callbackId];
if (callback) {
if (type === 'success') {
callback.success && callback.success(data);
} else {
callback.error && callback.error(data);
}
delete this.callbacks[callbackId]; // 执行后删除回调
}
},
};
function sendMessageToApp(message) {
const callbackId = window.callbacks.register(
(data) => console.log('Success:', data),
(error) => console.log('Error:', error)
);
window.ReactNativeWebView.postMessage(JSON.stringify({ callbackId, message }));
}
</script>
App 端实现
在 React Native 中,我们接收 Web 发送的消息,并根据 callbackId
返回结果:
import React, { useRef } from 'react';
import { WebView } from 'react-native-webview';
import { Button } from 'react-native';
const MyWebView = () => {
const webViewRef = useRef(null);
const onMessage = (event) => {
const { callbackId, message } = JSON.parse(event.nativeEvent.data);
// 模拟处理操作并返回结果
const result = `Processed: ${message}`;
const script = `
window.callbacks.execute('${callbackId}', 'success', ${JSON.stringify(result)});
`;
webViewRef.current.injectJavaScript(script);
};
return (
<WebView
ref={webViewRef}
source={{ uri: 'https://example.com' }}
onMessage={onMessage}
style={{ flex: 1 }}
/>
);
};
export default MyWebView;
解释
-
Web 端:使用
register
方法注册成功和失败回调,并将callbackId
通过postMessage
传递给 App。 -
App 端:在接收到消息后,根据
callbackId
处理数据,然后通过injectJavaScript
调用 Web 端的execute
方法来执行相应的回调。