react-native - onNavigationStateChange 不适用于我在 Angular 中的 WebView URL
问题描述
它只提供第一次加载的 URL(主 URL),无论我在哪里单击或想要在任何其他页面上导航,这应该是不同的。对于 SPA
<WebView
originWhitelist={['*']}
ref={c => this._webview = c}
source={{ uri: this.props.url }}
dataDetectorTypes={'all'}
onNavigationStateChange={this._onNavigationStateChange.bind(this)}
onLoadStart={this._webLoadStart.bind(this)}
onLoadEnd={this._webLoadEnd.bind(this)}
onError={this._webLoadError.bind(this)}
javaScriptEnabled={true}
domStorageEnabled={true}
allowUniversalAccessFromFileURLs={true}
/>
解决方案
SPA 应用程序不会触发 onLoad 事件,因此 navigationState 仅捕获第一个加载的 url。您需要在您的 WebView 中注入一个自定义 javascript,以通知 React Native 应用程序的 url 更改。
我建议如下:
如果 Angular 应用程序由您控制,则在每次 url 更改时使用 window.postMesssage 发送消息。
像这样的东西:
// create the function to notify React in your angular app
window.notifyReact = function(data, type){
if(window && window.postMessage) {
window.postMessage({data:data, type:type});
}
}
// use the function on every route change in your angular app
notifyReact({newUrl: "https://somenewurl/with-new-params"}, "URL_CHANGE")
然后在您的本机应用程序中,在您的 WebView 中侦听消息:
<WebView
...yourOtherProps
onMessage={e => {
const data = e && e.nativeEvent.data ? e.nativeEvent.data.data : null;
//print the data coming from the angular app to the console, data.newUrl should have the new url
console.log("data from angular app:", data);
}
}
/>
如果角度应用程序不受您控制,那么您最好的办法是在您的反应本机应用程序中加载 WebView 并拦截 url/hash 更改或来自window.history.pushState/popState。
祝你好运!
推荐阅读
- c++ - heap out of memory, noscript_shared_function_infos 持有的所有保留内存
- python - 根据文件名列表和目录列表将文件复制到新位置,但保留目录结构
- symfony4 - Symfony 4 / FosREST:API 路由返回 404 但不是 web 路由
- python - 如何计算熊猫列中带有日期时间的日期的剩余月份?
- c++ - 如何从http响应中删除垃圾数据
- .net - 如何修复应用服务的 Azure 部署槽问题?
- angular - 如何获取以前的搜索结果?
- asp.net-core - Razor Pages ASP.NET 不显眼的 ajax 发布部分更新
- php - 如何转换 1.5xxE-5
- javascript - ng-model 绑定没有正确更新