React Native WebView - Open link in external browser only in case of user interaction

Viewed 1744

I have the following WebView component that is used multiple times for various embeds inside news articles

<WebView
    useWebKit={true}
    ref={(ref) => this.webview = ref}
    javaScriptEnabled={true}
    injectedJavaScript={"(" + injectedScript + ")()"}
    onMessage={this.onMessage}
    onNavigationStateChange={this.onNavigationStateChange}
    {...this.props}
/>

and the following navigation state change listener, used for opening links in an external browser

onNavigationStateChange = (event) => {
    this.webview.stopLoading();
    Linking.openURL(event.url);
}

The problem is that the navigation change listener doesn't seem capable of differentiating between user interaction and automatic page redirects (which social media embeds will often do). How can I open the link in an external browser ONLY for user interaction?

1 Answers

I don't know exactly if automatic page redirects trigger click events, but they should not, so you can listen to only click events, which I suppose can only be triggered by the user.

onNavigationStateChange = (navState) =>
{
    if (navState.navigationType === 'click') {
        // User clicked something
    }
}
Related