I want to intercept clicks on a link in my webview in react-native and perform a custom action instead of navigating to the target of the link as described in the official guide. Here's what I do:
import React from 'react';
import {View, Linking} from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
import {WebView} from 'react-native-webview';
export default class WebViewScreen extends React.Component {
static navigationOptions = {
title: 'Produck',
};
constructor(props) {
super(props);
}
/**
* Defines content and look of the WebViewScreen.
*/
render() {
const DEFAULT_URL = "https://www.myurl.de/index.html";
return (
<View style={{ flex: 1 }}>
<WebView
ref = {webview => {
this.myWebView = webview;
}}
renderLoading = {this.renderLoading}
startInLoadingState = {true}
automaticallyAdjustContentInsets = {true}
source = {{ uri: DEFAULT_URL }}
javaScriptEnabled = {true}
domStorageEnabled = {true}
cacheEnabled = {false}
useWebKit = {true} // use WKWebView on iOS (http://facebook.github.io/react-native/blog/2018/08/27/wkwebview)
onNavigationStateChange={this.handleWebViewNavigationStateChange.bind(this)}
/>
</View>
);
}
handleWebViewNavigationStateChange = newNavState => {
const {url} = newNavState;
if (!url) return;
if (isExternal(url)) {
this.myWebView.stopLoading();
// do something else, e.g.
Linking.openURL(url);
}
};
}
If I click on a link in that webview the URL will be opened in a the systems Browser as expected. The problem is however that afterwards the webview is frozen. I can't click any more Links or even scroll the page. Of course this is not as it should be. The whole point is to open a link somewhere else so that the page in the webview remains usable. The result will remain the same, even if I remove the Linking
-part. Then the page just freezes on a link-click.
Does anyone know what to do? I guess the stopLoading-method does a little more than just abort loading. Does it maybe also cancel any running Javascript on the current page? If so, can I prevent that?