/* 监听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()
参考链接:
https://blog.csdn.net/liuxingyuzaixian/article/details/125199131
https://chat.xutongbao.top/