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/

相关推荐
cn_mengbei14 小时前
用React Native开发OpenHarmony应用:Reanimated共享元素过渡
javascript·react native·react.js
祖国的好青年3 天前
VS Code 搭建 React Native 开发环境(Windows 实战指南)
android·windows·react native·react.js
一个扣子3 天前
性能面板解读:通过 Hermes Runtime 测量函数执行耗时
react native·chrome devtools·hermes·性能面板·函数耗时·performance api
一个扣子5 天前
Hermes 的 Android 与 iOS 平台差异化配置详解
react native·字节码·新架构·hermes·android配置·ios配置·平台差异
茅盾体5 天前
React Native
android·react native·react.js
一个扣子6 天前
多环境配置:开发/生产环境下 Hermes 的开启与关闭策略
react native·开发模式·多环境配置·生产模式·hermes·环境切换·构建配置
TechMasterPlus7 天前
Hermes 深度解析:React Native 高性能 JavaScript 引擎实践指南
javascript·react native·react.js
令人头秃的代码0_07 天前
React Native Bundle更新升级
react native
用户600071819108 天前
【翻译】React Native JSI 深度解析(第 3 篇):面向 JavaScript 开发者的 C++
react native
Goway_Hui11 天前
【ReactNative鸿蒙化-三方库使用与C-API集成】
c语言·react native·harmonyos