React Native WebView 进阶:实现带回调函数的通讯

实现带回调的通讯

Web 端实现

在网页中,我们使用 window.callbacks 对象来注册回调函数,并将 callbackId 传递给 App:

html 复制代码
<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 返回结果:

javascript 复制代码
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;
解释
  1. Web 端 :使用 register 方法注册成功和失败回调,并将 callbackId 通过 postMessage 传递给 App。

  2. App 端 :在接收到消息后,根据 callbackId 处理数据,然后通过 injectJavaScript 调用 Web 端的 execute 方法来执行相应的回调。

相关推荐
天若有情67318 小时前
程序员原创|借鉴JS事件冒泡,根治电脑文件混乱的“冒泡整理法”
开发语言·javascript·windows·ecmascript·电脑·办公·日常
FYKJ_201019 小时前
springboot校园兼职平台--附源码02041
java·javascript·spring boot·python·eclipse·django·php
沐言人生1 天前
React Native 源码分析1——HybridData 机制深度分析
android·react native
空中海1 天前
01 React Native 基础、核心组件与布局体系
javascript·react native·react.js
空中海1 天前
05 React架构设计、项目实践与专家清单
前端·react.js·前端框架
前端之虎陈随易1 天前
2年没用Nodejs了,Bun很香
linux·前端·javascript·vue.js·typescript
空中海1 天前
04 工程化、质量体系与 React 生态
前端·ubuntu·react.js
Yue1681 天前
一文教你五分钟学会Zustand,React状态管理更加方便!
react native
空中海1 天前
03 性能、动画与 React Native 新架构
react native·react.js·架构
好运的阿财1 天前
OpenClaw工具拆解之host_workspace_write+host_workspace_edit
前端·javascript·人工智能·机器学习·ai编程·openclaw·openclaw工具