首页 > 解决方案 > 如何从浏览器单击从 react-native-webview 访问下一个 url

问题描述

我有一个使用 react-native-webview 打开的 webview 源,我想在单击 webview 时访问任何和每个 url 并对其进行控制台,以便我可以将其用作另一个 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 的新来源。任何建议都会很棒。

标签: reactjsreact-nativewebviewreact-navigationreact-native-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)
}

仅供参考 webviewState 对象包括,使用 url 属性:

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

让我知道是否有帮助


推荐阅读