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/

相关推荐
soul968162 小时前
react-native-promise-portal:React Native 弹窗管理的新思路
react native
是一碗螺丝粉1 天前
React Native 运行时深度解析
前端·react native·react.js
努力往上爬de蜗牛3 天前
react native真机调试
javascript·react native·react.js
o***Y3633 天前
鸿蒙NEXT(五):鸿蒙版React Native架构浅析
react native·架构·harmonyos
5***a9753 天前
React Native性能优化技巧
javascript·react native·react.js
wordbaby4 天前
React Native 进阶实战:基于 Server-Driven UI 的动态表单架构设计
前端·react native·react.js
胡琦博客5 天前
21天开源鸿蒙训练营|Day2 ReactNative 开发 OpenHarmony 应用环境搭建实录
javascript·react native·react.js
6***37945 天前
React Native热更新方案
javascript·react native·react.js
x***J3485 天前
React Native组件封装
javascript·react native·react.js
E***U9455 天前
React Native开发
android·react native·react.js