Search code examples
react-nativewebview

How can i detect a touch event in React Native WebVIew


My application uses WebView to open external webpage, now when my user click on any link within this webview i want to get the URL from the WebView and then do something with the uri in my App and also terminate Webview so it won't continue to open the url in webView or broswer


Solution

  • Alright lets assume you have this code structure

    import { WebView } from 'react-native-webview';
    
    const Test = () => {
     const handleUrlLoading = (request) => {
      const { url } = request;
      if (shouldHandleUrl(url)) {
       console.log("Handling URL internally:", url);
       return false;
      }
      return false;   //return true; if you still want to open other url inside WebView
     };
     return (
      <WebView
       source={{ uri: 'https://example.com' }}
       onShouldStartLoadWithRequest={handleUrlLoading}
      />
     );
    }
    function shouldHandleUrl(url) {
     return url.includes('https://www.iana.org/help/example-domains');
    }
    

    Note that in shouldHandleUrl I explicitly hardcoded the url that the page contains, so the function will be triggered when the user interact in the WebView once a request will be fired on, it will match the url that we are targeting, then prevent it from opening in the WebView, but console log it instead, And finally to redirect outside of the app here is a snippet code:

    Linking.openURL(url).catch(err => {console.error("Failed to open URL:", err);});