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/

相关推荐
前端小D6 天前
React Native项目开发(iOS侧为例)
javascript·react native·react.js
大龄秃头程序员7 天前
从源码里看懂 React Native 新架构:TurboModule 与 Fabric 到底是怎么跑起来的?
react native
前端小D8 天前
React Native Android 项目搭建
android·react native·react.js
hhhjhl10 天前
React Native 三方库「react-native-sha256」的鸿蒙化适配指南
react native·华为·harmonyos
2601_9499706910 天前
React Native 三方库「react-native-version-check」的鸿蒙化适配指南
react native·华为·harmonyos
hhhjhl10 天前
React Native 三方库「react-native-proximity」的鸿蒙化适配指南
react native·华为·harmonyos
2601_9499706910 天前
React Native 三方库「react-native-media-notification」的鸿蒙化适配指南
react native·华为·harmonyos
GitCode官方10 天前
从大语言模型到具身智能:百度百舸 LoongForge 入驻 AtomGit
人工智能·react native·百度·harmonyos·atomgit
2501_9159184113 天前
Windows 上开发 React Native iOS,真机调试、Fast Refresh 与打包 ipa
windows·vscode·react native·ios·个人开发·swift·敏捷流程
2501_9481226314 天前
Qs 跨端三方库仓颉适配全流程
python·react native·django·tornado