webview onNavigationStateChange returns url of previous page

12,043

Sadly, all the webview methods like onNavigationStateChange, onLoad, onLoadStart etc are not working as expected in cases of single page application websites or websites that don't trigger a window.load event.

Normaly onNavigationStateChange gets triggered in the beginning of a request with {loading: true, url: "someUrl", ...} and once after the loading of the url with {loading: false, url: "someUrl", ...}.

There is no global workaround (to my knowledge) that will work correctly for all websites and for both iOs/Android but maybe this can help in your case:

https://snack.expo.io/H1idX8vpM

Basically you inject a custom javascript in the webview that notifies the WebView which is the loaded page. You can enhance it if you want to catch custom window.history manipulation events.

Share:
12,043
Vishal Deep
Author by

Vishal Deep

Updated on December 04, 2022

Comments

  • Vishal Deep
    Vishal Deep over 1 year

    In react native webview, when I navigate to a page the onNavigationStateChange returns url of the previous page? I think its an issue and posted it to github react native issues.

      <WebView
       ref={r => this.webview = r}
       style = {{marginTop : 0}}
       onNavigationStateChange= 
       {this._onNavigationStateChange.bind(this)}
             startInLoadingState = {true}
             source = {{uri: 'https://www.youtube.com' }}
        />
        
       _onNavigationStateChange(webViewState)
         {
           this.setState(
                {
                   youtube_video_url: webViewState.url
                }) 
             }
    

    When I print this youtube_video_url, it is of the previous page or previous browsed video.

    • Claudia
      Claudia almost 6 years
      Welcome to Stack Overflow! It seems you have a problem with your code. However, we can't help unless we have code or information that can reproduce the problem. Otherwise, we are just blindly guessing.
    • Vishal Deep
      Vishal Deep almost 6 years
      I have edited the question by adding the required code.