Anoop Mundathan
Anoop Mundathan

Reputation: 245

How to open external link in browser from inside Webview in React Native?

I have below webview component, I wanted the link to be opened in a mobile browser app rather than in inside current webview in my app.

return() {
    <WebView source={{ html: `<a href="https://www.google.com">Google</a>`}} />
}

Upvotes: 0

Views: 14361

Answers (4)

mainak
mainak

Reputation: 2311

Try this one. This will save your time and patience :)

 import HTML from 'react-native-render-html';
    <HTML
        html={this.state.content.description} 
        // imagesMaxWidth={Dimensions.get('window').width} 
        onLinkPress={(evt, href) => { Linking.openURL(href) }}
    />

Upvotes: 0

iqqmuT
iqqmuT

Reputation: 843

Calling stopLoading freezes the WebView and links may stop working after pressing them once. Better to use onShouldStartLoadWithRequest (API Reference).

So the code could look something like this:

import { Linking } from 'react-native';
import { WebView } from 'react-native-webview';

const html = ` 
 <a href="https://www.google.com">Google</a>
 <a href="https://www.twitter.com">Twitter</a>
`;

const shouldStartLoadWithRequest = (req) => {
  // open the link in native browser
  Linking.openURL(req.url);

  // returning false prevents WebView to navigate to new URL
  return false;
};

const MyComponent = () => (
  <WebView
    originWhitelist={['*']}
    source={{ html }}
    onShouldStartLoadWithRequest={shouldStartLoadWithRequest}
  />
);

export default MyComponent;

Note that onShouldStartLoadWithRequest behaves a bit differently on iOS.

Upvotes: 2

Calixto
Calixto

Reputation: 585

you can do this:

import { Linking } from 'react-native';

on you launch function

Linking.openURL( some_url );

For more details, follow this full example: Just what you want

Upvotes: 3

Anoop Mundathan
Anoop Mundathan

Reputation: 245

This worked for me.

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

const html = ` 
 <a href="https://www.google.com">Google</a>
 <a href="https://www.twitter.com">Twitter</a>
`

class WebViewWrapper extends Component {
    private webview;

    handleNavigationStateChange = (event: NavState) => {
        if (event.url) {
            this.webview.stopLoading();
            Linking.openURL(event.url);
        }
    };

    render() {
        return (
            <WebView
                originWhitelist={['*']}
                ref={ref => {
                   this.webview = ref;
                }}
                source={{ html }}
                onNavigationStateChange={this.handleNavigationStateChange}
            />
        );
    }
}

Upvotes: 5

Related Questions