首页 > 解决方案 > 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}
/>

标签: react-native

解决方案


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。

祝你好运!


推荐阅读