经过几天的努力,我找到了以下解决方案,我承认这有点难以理解,但可以完美地运行(包括返回按钮和手势):
在React Web应用程序中,我通过全局Window对象保留了ReactRouter历史记录对象。
import { useHistory } from 'react-router'
declare global {
interface Window {
ReactRouterHistory: ReturnType<typeof useHistory>
}
}
const AppContextProvider = props => {
const history = useHistory()
window.ReactRouterHistory = history
}
在React Native移动应用中,我注入了自定义代码到WebView中,该代码利用history对象进行导航,应用程序使用消息与此代码通信:
webViewScript.ts
export default `
const handleMessage = (event) => {
var message = JSON.parse(event.data)
switch (message.type) {
// ...
case '${MessageTypes.NAVIGATE}':
if (message.params.uri && message.params.uri.match('${APP_URL}') && window.ReactRouterHistory) {
const url = message.params.uri.replace('${APP_URL}', '')
window.ReactRouterHistory.push(url)
}
break
}
};
!(() => {
function sendMessage(type, params) {
var message = JSON.stringify({type: type, params: params})
window.ReactNativeWebView.postMessage(message)
}
if (!window.appListenersAdded) {
window.appListenersAdded = true;
window.addEventListener('message', handleMessage)
var originalPushState = window.history.pushState
window.history.pushState = function () {
sendMessage('${MessageTypes.PUSH_STATE}', {state: arguments[0], title: arguments[1], url: arguments[2]})
originalPushState.apply(this, arguments)
}
}
})()
true
`
intercom.ts
(这里没有路由特定的内容,只是用于通用通信)
import WebView, {WebViewMessageEvent} from 'react-native-webview'
import MessageTypes from './messageTypes'
export const sendMessage = (webview: WebView | null, type: MessageTypes, params: Record<string, unknown> = {}) => {
const src = `
window.postMessage('${JSON.stringify({type, params})}', '*')
true // Might fail silently per documentation
`
if (webview) webview.injectJavaScript(src)
}
export type Message = {
type?: MessageTypes,
params?: Record<string, unknown>
}
export type MessageHandler = (message: Message) => void
export const handleMessage = (handlers: Partial<Record<MessageTypes, MessageHandler>>) => (
(event: WebViewMessageEvent) => {
const message = JSON.parse(event.nativeEvent.data) as Message
const messageType = message.type
if (!messageType) return
const handler = handlers[messageType]
if (handler) handler(message)
}
)
export {default as script} from './webViewScript'
WebViewScreen.tsx
import {handleMessage, Message, script, sendMessage} from '../intercom'
const WebViewScreen = ({navigation, navigationStack}: WebViewScreenProps) => {
const messageHandlers = {
[MessageTypes.PUSH_STATE]: ({params}: Message) => {
if (!params) return
const {url} = params
const fullUrl = `${APP_URL}${url}`
navigationStack.push(fullUrl)
},
}
const uri = navigationStack.currentPath
useEffect(() => {
if (uri) {
sendMessage(webViewRef.current, MessageTypes.NAVIGATE, {uri})
}
}, [uri])
const source = useMemo(() => ({uri}), [])
return (
<View
// ...
refreshControl={
<RefreshControl
// ...
/>
}
>
<WebView
source={source}
injectedJavaScript={script}
onMessage={handleMessage(messageHandlers)}
// ...
/>
</View>
)
}