Reputation: 578
I have a WebView that contains multiple links. If one of those links is pressed and it has a target = "_blank" attribute how do I open it in default browser?
<WebView
ref={webViewRef}
source={{ uri: 'www.randomwebsite.com' }}
onNavigationStateChange={event => {
if (event.navigationType === 'click' ) { //how to test for **a href** with **target blank** ?
Linking.openURL(event.url);
}
}}
/>
Upvotes: 1
Views: 5336
Reputation: 1
expo install react-native-webview expo install expo-web-browser
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { SafeAreaView } from 'react-native';
import { WebView } from 'react-native-webview';
import * as WebBrowser from 'expo-web-browser';
export default () => {
const uri = 'http://localhost';
return (
<SafeAreaView style={{ flex: 1, backgroundColor: '#ffffff' }} >
<StatusBar style="dark" />
<WebView style={styles.container} source={{ uri }}
onShouldStartLoadWithRequest={(event) => {
if (!event.url.includes(uri)) {
WebBrowser.openBrowserAsync(event.url);
return false
} else {
return true
}
}}
/>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
marginTop: 30
}
});
Upvotes: 0
Reputation: 1940
This is a minimalistic example below
Working example: https://snack.expo.io/@msbot01/upbeat-scones
import * as React from 'react';
import { View, Text, Image, Linking } from "react-native";
import { WebView } from 'react-native-webview';
import * as WebBrowser from 'expo-web-browser';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
uri: 'https://www.google.com/'
}}
render() {
return (
<WebView
source={{ uri: this.state.uri }}
onNavigationStateChange={ (event) => {
console.log('::::::::'+event.url)
console.log('+++++'+this.state.uri)
if(this.state.uri !== event.url ){
console.log('Match not found')
Linking.openURL(event.url);
}
}}
/>
)
}
}
Upvotes: 1