React Native - open links in browser

前端 未结 13 716
遇见更好的自我
遇见更好的自我 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:37

    This is my solution. As it is not generic, you can improve the injected javascript according to your requirements

    import {
      View,
      WebView,
      Linking,
    } from 'react-native';
    
    const injectScript = `
      (function () {
        window.onclick = function(e) {
          e.preventDefault();
          window.postMessage(e.target.href);
          e.stopPropagation()
        }
      }());
    `;
    
    class MyWebView extends React.Component {
    
      onMessage({ nativeEvent }) {
        const data = nativeEvent.data;
    
        if (data !== undefined && data !== null) {
          Linking.openURL(data);
        }
      }
    
      render() {
        return (
          
        )
      }
    }
    

提交回复
热议问题