Redirect WebView with other domain in React Native

I'm trying to redirect links from another domain to the device's default browser.

For example:

I tried a lot of things, but I still can not make it work. I think about using onNavigationStateChange with Linking.

Thanks for your help.

import React from 'react';
import { StyleSheet, View, WebView } from 'react-native';
import { Constants } from 'expo';


export default class App extends React.Component {

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.statusBar} />
        <WebView
          source={{uri: 'https://example.com'}}
          renderError={() => alert('Merci de vérifier votre connexion Internet', 'Internet non disponible')}
        />
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  statusBar: {
    backgroundColor: "#1D3B57",
    height: Constants.statusBarHeight,
  }
});

1 answer

  • answered 2018-04-14 15:44 Stackia

    Solution 1:

    onNavigationStateChange(e)
    {
      if(e.url !== this.state.oldUrl)
      {
        // If url changed
        if(/youtube.com/.test(e.url)) // RegExp
        {
            this.refs.WEBVIEW_REF.goBack()
            Linking.canOpenURL(e.url).then(supported => {
              if (supported) return Linking.openURL(e.url)
            })
        }
        this.setState({ oldUrl: e.url })
      }
    }
    

    Solution 2:

    Consider looking into this PR to expose native shouldOverrideUrlLoading method to JS. It might be a bit complex to do this.