如何通过浏览器从react-native-webview

问题描述

我有一个使用react-native-webview打开的Webview源,我想访问任何URL并在每次单击该Webview时对其进行管理,以便可以将其用作另一个Webview的源。但是无法弄清楚怎么做

我尝试使用NavigationStateChange和onShouldLoadSTartwithrequest,但这没有帮助。

下面是我的代码

import React,{useState,useRef,useEffect} from 'react';
import {WebView} from 'react-native-webview';
import {
  View,SafeAreaView,ActivityIndicator,StyleSheet,TouchableOpacity,Text,Linking,Alert,BackHandler,} from 'react-native';
import Footer from '../components/Footer';
import {useBackHandler} from '@react-native-community/hooks';
import OnlineConsultationWebviewScreen from './OnlineConsultationWebviewScreen';
export default function ConsultationHomeScreen(props) {
  const uri = props.route.params.uri;
  const [canGoBack,setCanGoBack] = useState(false);
  const [canGoForward,setCanGoForward] = useState(false);
  const [currentUrl,setCurrentUrl] = useState('');
  const webviewRef = useRef(null);

  const renderLoadingView = () => {
    return (
      <View style={{flex: 1,alignItems: 'center',justifyContent: 'center'}}>
        <ActivityIndicator size="large" />
      </View>
    );
  };
  const onMessage = (e) => {
    // retrieve event data
    var data = e.nativeEvent.data;
    // maybe parse stringified JSON
    try {
      data = JSON.parse(data);
    } catch (e) {}
    // check if this message concerns us
    if ('object' == typeof data && data.external_url_open) {
      // proceed with URL open request
      return Alert.alert(
        'External URL','Do you want to open this URL in your browser?',[
          {text: 'Cancel',style: 'cancel'},{text: 'OK',onPress: () => Linking.openURL(data.external_url_open)},],{cancelable: false},);
    }
  };
  const jsCode = `!function(){var e=function(e,n,t){if(n=n.replace(/^on/g,""),"addEventListener"in window)e.addEventListener(n,t,!1);else if("attachEvent"in window)e.attachEvent("on"+n,t);else{var o=e["on"+n];e["on"+n]=o?function(e){o(e),t(e)}:t}return e},n=document.querySelectorAll("a[href]");if(n)for(var t in n)n.hasOwnProperty(t)&&e(n[t],"onclick",function(e){new RegExp("^https?://"+location.host,"gi").test(this.href)||(e.preventDefault(),window.postMessage(JSON.stringify({external_url_open:this.href})))})}();`;
  return (
    <SafeAreaView style={{flex: 1}}>
      <WebView
        source={{
          uri: uri,}}
        renderLoading={renderLoadingView}
        javaScriptEnabled={true}
        domStorageEnabled={true}
        startInLoadingState={true}
        ref={webviewRef}
        injectedJavaScript={jsCode}
        onMessage={onMessage}
        onError={console.error.bind(console,'error')}
        // onShouldStartLoadWithRequest={(event) => {
        //   if (event.url !== uri ){
        //     Linking.openURL(event.url);
        //     console.log('Event',event.url);
        //     return false;
        //   }
        //   return true;
        // }}
      />
    </SafeAreaView>
  );
}
const styles = StyleSheet.create({
  tabBarContainer: {
    padding: 20,flexDirection: 'row',justifyContent: 'space-around',backgroundColor: '#b43757',},button: {
    color: 'white',fontSize: 24,});

很久以来,我一直对此深信不疑,请让我知道如何访问任何单击并进行管理,以便以后可以起诉它作为Webview的新来源。 任何建议都会很棒。

解决方法

尝试一下:

<WebView
   ref="webview"
   source={uri}
   onNavigationStateChange={this._onNavigationStateChange.bind(this)}
   javaScriptEnabled = {true}
   domStorageEnabled = {true}
   injectedJavaScript = {this.state.cookie}
   startInLoadingState={false}
 />

添加此功能:

_onNavigationStateChange(webViewState){
 console.log(webViewState.url)
}

FYI webviewState对象组成,请使用url属性:

{
canGoBack: bool,canGoForward: bool,loading: bool,target: number,title: string,url: string,}

让我知道是否有帮助