react-native-webview: distinguish between window.location caused by script and user clicking the link

Viewed 706

Is there a way in react-native-webview to distinguish between user-caused and script-caused navigations?

I see that onLoad[Start,End] and onNavigationStateChange events are fired in both cases. Also, if I add logging to WebViewClient.shouldOverrideUrlLoading() or WebViewClient.shouldInterceptRequest(), both fns are invoked if either window.location is changed inside a script, or if user clicks a link. So how can one distinguish these two?

Thanks!

EDIT: have to clarify, that I have no control over what scripts are loaded and what they are doing on the page.

1 Answers

you can pass query param isUserCause=true in every window.location in user-caused on website end and onNavigationStateChange you can detect isUserCause params

you can pass url like this

http://www.example.com/index.php?isUserCause=true

and in onNavigationStateChange you can parse query params by QS pacakge

import qs from 'qs';

getQueryParams = (url) => {
    var regex = /\?.+/g;
    const result = url.match(regex);
    if (result && result.length>0) {
      const parsed = qs.parse(result[0], {ignoreQueryPrefix: true});
      return parsed;
    } else {
      return {};
    }
  };


onNavigationStateChange = (navState) => {
    const queryParams=this.getQueryParams(navState.url);
    if(queryParams.isUserCause)
    {
      console.log("user-caused");
    }
    else
    {
      console.log("script-caused");
    }
  };
Related