react-native-webview使用postMessage后H5不能监听问题(iOS和安卓的兼容问题)

javascript 复制代码
/* 监听rn消息 */
const eventListener = nativeEvent => {
    //解析数据actionType、extra
    const {actionType, extra} = nativeEvent.data && JSON.parse(nativeEvent.data) || {}
}
//安卓用document,ios用window
window.addEventListener('message', eventListener);
document.addEventListener('message', eventListener);
javascript 复制代码
import uaParser from 'ua-parser-js'

let timer
let ua = uaParser(navigator.userAgent)

const handleWatchRNMessage = () => {
  if (window.ReactNativeWebView) {
    window.ReactNativeWebView.postMessage(JSON.stringify({ type: 'getToken' }))
  }

  const eventListener = (e) => {
    console.log('message', e.data)
    let payload = e.data ? JSON.parse(e.data) : {}
    let type = payload.type

    if (type === 'getToken') {
      localStorage.setItem('token', payload.token)
    } else if (type === 'getBrowserInfo') {
      const { browser } = ua
      window.ReactNativeWebView.postMessage(JSON.stringify({ type, browser }))
    }
  }

  if (window.platform === 'rn') {
    if (ua.os.name === 'iOS') {
      window.addEventListener('message', eventListener)
    } else {
      window.document.addEventListener('message', eventListener)
    }
  }
}

handleWatchRNMessage()

参考链接:

https://blog.csdn.net/liuxingyuzaixian/article/details/125199131

https://chat.xutongbao.top/

相关推荐
哼唧唧_14 小时前
使用 React Native 开发鸿蒙(HarmonyOS)运动健康类应用的系统化准备工作
react native·react.js·harmonyos·harmony os5·运动健康
哼唧唧_2 天前
React Native开发鸿蒙运动健康类应用的项目实践记录
react native·harmonyos·harmony os5·运动健康
程序员小刘3 天前
鸿蒙【HarmonyOS 5】 (React Native)的实战教程
react native·华为·harmonyos
烈焰晴天3 天前
使用ReactNative加载Svga动画支持三端【Android/IOS/Harmony】
android·react native·ios
哼唧唧_3 天前
使用 React Native 开发鸿蒙运动健康类应用的高频易错点总结
react native·react.js·harmonyos·harmony os5·运动健康
鄂鱼4 天前
使用react-native-skia实现自绘地图实践与踩坑记录
react native
依旧004 天前
react native webview加载本地HTML,解决iOS无法加载成功问题
react native·ios·html·vite·webview
不想当reducer4 天前
React Native 阿里云 OSS 上传实战:从相册资源处理到动态签名管理
前端·javascript·react native
hellokai5 天前
ReactNative介绍及简化版原理实现
android·react native
哼唧唧_6 天前
基于React Native开发鸿蒙新闻类应用的实战开发笔记
react native·华为·新闻·harmony os5