React Native - open links in browser

前端 未结 13 718
遇见更好的自我
遇见更好的自我 2020-12-04 11:59

Hi i am using react native\'s webview to display some html, i want that whenever a user clicks a link inside that html, it will open the user\'s browser with that link.

13条回答
  •  猫巷女王i
    2020-12-04 12:34

    I found a way to do this, it is an iOS-only solution though!

    Here is step-by-step instructions:

    1. Link the 'RCTLinkingIOS' library to your project. I used CocoaPods to so.
    2. In your WebView add "onShouldStartLoadWithRequest". For example

    3. Add the this.onShouldStartLoadWithRequest function. Return TRUE or FALSE based on whether or not you want to follow the link in your WebView. This is basically the equivalent of the UIWebViewDelegate implementation you would use when you implement it in native code (Swift or Objective-C).

      onShouldStartLoadWithRequest = (event) => {
           Linking.canOpenURL(event.url).then(supported => {
               if (supported) {
                   Linking.openURL(event.url);
               } else {
                   console.log('Don\'t know how to open URI: ' + event.url);
               }
               return false
           });
      }
      
    4. Make sure to import Linking as well in your javascript source:

      import { AppRegistry, View, WebView, Linking } from 'react-native';

    That should do the trick.

    For more information see the react-native docs: https://facebook.github.io/react-native/docs/linking.html

提交回复
热议问题