chatgpt:
https://chat.xutongbao.top/文章来源地址https://www.toymoban.com/news/detail-652822.html
/* 监听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://www.toymoban.com/news/detail-652822.html
https://chat.xutongbao.top/
到了这里,关于react-native-webview使用postMessage后H5不能监听问题(iOS和安卓的兼容问题)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!