react-native-webview使用postMessage后H5不能监听问题(iOS和安卓的兼容问题)

/* 监听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);

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()

react-native-webview使用postMessage后H5不能监听问题(iOS和安卓的兼容问题)_第1张图片

 

参考链接:

https://blog.csdn.net/liuxingyuzaixian/article/details/125199131

https://chat.xutongbao.top/ 

你可能感兴趣的:(web前端,react,native)