Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native Deep Link from within WebView

I'm using React Native with React Navigation and react-native-deep-linking and react-native-webview packages.

My app is using deep linking to reach different screens of the app, and it is working fine to open the deep link on the iPhone except from within WebView where nothing happens if I press the link. The app does not even react on clicking on the link, no console.warn message or so neither.

If I use Safari on the iPhone instead, the functions works just fine, but not from within WebView.

This is the WebView code:

class BankID extends React.Component {
  render() {
      return (
        <WebView
          style={{ flex: 1 }}
          source={{ uri: 'https://URL/file.html' }}
        />
      );
  }
}
export default BankID;

file.html:

<html>
<body>
<a href="test://1234">App-Link</a>
</body>
</html>

And from App.js I've got the deep linking component as instructed in the github repo:

componentDidMount() {
  DeepLinking.addScheme('test://');

  Linking.addEventListener('url', this.handleUrl);

    Linking.getInitialURL().then((url) => {
      if (url) {
        Linking.openURL(url);
      }
    }).catch(err => console.error('An error occurred', err));

    DeepLinking.addRoute('/:id', ({ id }) => {
      this.setState({ roomKey: id.toString() });
      if (this.vidyoConnector) {
        this.callButtonPressHandler();
      }
    });
 }
  handleUrl = ({ url }) => {
    Linking.canOpenURL(url).then((supported) => {
      if (supported) {
        DeepLinking.evaluateUrl(url);
      }
    }).catch((error) => {
      console.warn('handleUrl failed with the following reason: ', error);
    });
  }

Any help would be much appreciated. Thank you.

like image 257
SimonB Avatar asked Jan 18 '19 05:01

SimonB


1 Answers

This worked for me:

in the webview I added onShouldStartLoadWithRequest with a function.

  <WebView
    other
    stuff
    onShouldStartLoadWithRequest={this.openExternalLink}
  />

and then the function:

  openExternalLink= (req) => {
    const isHTTPS = req.url.search('https://') !== -1;

        if (isHTTPS) {
          return true;
        } else {
          if (req.url.startsWith("test://")) {
            this.props.navigation.navigate('Home');
          } 
          return false;
        }
      }

Didn't have to change anything in App.js

like image 51
SimonB Avatar answered Oct 04 '22 03:10

SimonB