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/

相关推荐
光影少年5 小时前
React Native项目常见的性能瓶颈有哪些?(JS线程阻塞、UI渲染卡顿、内存泄漏、包体积过大)
javascript·react native·ui
弓.长.1 天前
ReactNative for OpenHarmony项目鸿蒙化三方库:lottie-react-native — Lottie动画组件
react native·react.js·harmonyos
CC_Amber1 天前
RN 0.63 双端冷启动线程流转
react native
CC_Amber1 天前
Flexbox 在 RN 中的行为差异 & css注意
react native
CC_Amber1 天前
浅谈 RN新架构与老架构
react native
弓.长.1 天前
ReactNative for OpenHarmony项目鸿蒙化三方库:react-native-flash-message — 闪现消息组件
react native·react.js·harmonyos
弓.长.1 天前
ReactNative for OpenHarmony项目鸿蒙化三方库:react-native-snap-carousel — 轮播组件
react native·react.js·harmonyos
弓.长.1 天前
ReactNative for OpenHarmony项目鸿蒙化三方库:react-native-animatable — 动画组件
react native·react.js·harmonyos
CC_Amber1 天前
RN线程模型
react native
弓.长.1 天前
ReactNative for OpenHarmony项目鸿蒙化三方库:react-native-shimmer-placeholder — 骨架屏组件
react native·react.js·harmonyos