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/

相关推荐
坚果派·白晓明6 小时前
Windows 11 OpenHarmony版React Native开发环境搭建完整指南
react native·开源鸿蒙·rnoh
开心不就得了1 天前
React Native对接Sunmi打印sdk
javascript·react native·react.js
Joyee6912 天前
RN 的初版架构——运行时异常与异常捕获处理
react native·前端框架
前端不太难2 天前
RN 列表状态设计 Checklist
react native·list·状态模式
hongkid2 天前
React Native 如何打包正式apk
javascript·react native·react.js
光影少年2 天前
前端如何虚拟列表优化?
前端·react native·react.js
千里马-horse3 天前
Rect Native bridging 源码分析--Bool.h
javascript·c++·react native·react.js·bool
千里马-horse3 天前
Rect Native bridging 源码分析--Dynamic.h
javascript·react native·react.js·dynamic
千里马-horse3 天前
Rect Native bridging 源码分析--Array.h
javascript·c++·react native·react.js·bridging
千里马-horse4 天前
React Native 源码分析 -- jsi.h
javascript·c++·react native·react.js·jsi