React Native - open links in browser

前端 未结 13 701
遇见更好的自我
遇见更好的自我 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条回答
  •  春和景丽
    2020-12-04 12:41

    Here is a complete working solution:

    import React, { Component } from 'react';
    import { WebView, Linking } from 'react-native';
    
    export default class WebViewThatOpensLinksInNavigator extends Component {
      render() {
        const uri = 'http://stackoverflow.com/questions/35531679/react-native-open-links-in-browser';
        return (
           { this.webview = ref; }}
            source={{ uri }}
            onNavigationStateChange={(event) => {
              if (event.url !== uri) {
                this.webview.stopLoading();
                Linking.openURL(event.url);
              }
            }}
          />
        );
      }
    }
    

    It uses a simple WebView, intercepts any url change, and if that url differs from the original one, stops the loading, preventing page change, and opens it in the OS Navigator instead.

提交回复
热议问题