Home > other >  React Native WebView if url Match show alert to exit
React Native WebView if url Match show alert to exit

Time:11-02

react webview backhandler works fine when i insert condition if url match to show alert not working here below code is

 const [canGoBack, setCanGoBack] = useState(false);
 const [canGoForward, setCanGoForward] = useState(false);
 const [currentUrl, setCurrentUrl] = useState('');


  const onPressHardwareBackButton = () => {
 
    if (webview.current) { 
      webview.current.goBack();
       return true; 

    } else {
      return false;
    }
  
  };
 useEffect(() => {
 
        BackHandler.addEventListener('hardwareBackPress', onPressHardwareBackButton);
        return () => {
          BackHandler.removeEventListener('hardwareBackPress', onPressHardwareBackButton);
        }
    
  }, []);

<WebView 
      source={{ uri: 'https://example.com/' }} 
      ref={webview}
       onNavigationStateChange={(navState) => {
        setCanGoBack(navState.canGoBack);
        setCanGoForward(navState.canGoForward);
        setCurrentUrl(navState.url);
      }}
             />

if CurrentUrl matches like www.example.com/dashboard need to alert

  Alert.alert("Hold on!", "Are you sure you want to go back?", [
    {
      text: "Cancel",
      onPress: () => null,
      style: "cancel"
    },
    { text: "YES", onPress: () => BackHandler.exitApp() }
  ])  

how can achieve this

CodePudding user response:

You are already saving the current url to state so just listening the currentUrl changes should be enough.

useEffect(() => {
    if(currentUrl === 'www.example.com/dashboard') {
        Alert.alert("Hold on!", "Are you sure you want to go back?", [
            {
              text: "Cancel",
              onPress: () => null,
              style: "cancel"
            },
            { text: "YES", onPress: () => BackHandler.exitApp() }
         ]);
    }
}, [currentUrl]);
  • Related