使用 React Native 中的其他域重定向 WebView



我正在尝试将链接从另一个域重定向到设备的默认浏览器。

例如:

  • 如果链接 http://domain.io,请留在 Web 视图中;
  • 如果链接是http://domain.io/page,我们停留在网络视图中;
  • 如果链接是http://mylink.io/,我们将用户重定向到设备,我们离开网络视图。

我尝试了很多东西,但我仍然无法让它工作。我考虑将onNavigationStateChange与链接一起使用。

感谢您的帮助。

import React from 'react';
import { StyleSheet, View, WebView } from 'react-native';
import { Constants } from 'expo';

export default class App extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <View style={styles.statusBar} />
        <WebView
          source={{uri: 'https://example.com'}}
          renderError={() => alert('Merci de vérifier votre connexion Internet', 'Internet non disponible')}
        />
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  statusBar: {
    backgroundColor: "#1D3B57",
    height: Constants.statusBarHeight,
  }
});

解决方案 1:

onNavigationStateChange(e)
{
  if(e.url !== this.state.oldUrl)
  {
    // If url changed
    if(/youtube.com/.test(e.url)) // RegExp
    {
        this.refs.WEBVIEW_REF.goBack()
        Linking.canOpenURL(e.url).then(supported => {
          if (supported) return Linking.openURL(e.url)
        })
    }
    this.setState({ oldUrl: e.url })
  }
}

解决方案 2:

请考虑研究此 PR 以向 JS 公开本机shouldOverrideUrlLoading方法。这样做可能有点复杂。

最新更新