解决React Native 自带的WebView组件Android不能拦截URL的问题
npm install react-native-android-webview --save
-
Add the following lines to
android/settings.gradle
:include ':react-native-android-webview' project(':react-native-android-webview').projectDir = new File(settingsDir, '../node_modules/react-native-android-webview')
-
Add the compile and resolutionStrategy line to the dependencies in
android/app/build.gradle
:dependencies { compile project(':react-native-android-webview') }
-
Add the import and link the package in
MainApplication.java
:import com.zsc.RNWebViewPackage; //<-- add this import public class MainApplication extends Application implements ReactApplication { @Override protected List<ReactPackage> getPackages() { return Arrays.<ReactPackage>asList( new MainReactPackage(), new RNWebViewPackage() // <-- add this line ); } }
-
Ensure Android SDK versions. Open your app's
android/app/build.gradle
file. EnsurecompileSdkVersion
andtargetSdkVersion
are 23. Otherwise you'll get compilation errors.
- import
import WebViewAndroid from 'react-native-android-webview'
- custom intercept func
onShouldStartLoadWithRequest
onShouldStartLoadWithRequest = (event) => {
var url = event.url;
if (url && url.length) {
if (url.indexOf('news.baidu') >= 0) {
alert('被拦截')
return false;
}
}
return true;
};
- UI add
WebViewAndroid
Component
render() {
return (
<View style={styles.container}>
<WebViewAndroid
ref={'webview'}
injectFilterInterceptArray={["news.baidu"]}
allowInterceptUrl={true}
style={{
backgroundColor:'#ffffff'
}}
source={{
uri: 'http://www.baidu.com'
}}
scalesPageToFit={false}
onShouldStartLoadWithRequest={this.onShouldStartLoadWithRequest}
/>
</View>
);
}