Mohit Goel
Mohit Goel

Reputation: 742

React Native webview onNavigationStateChange is not getting called in web app (chrome)

I'm working on a React Native application that uses react-native-webview to load a third-party URL. I implemented the onNavigationStateChange callback to handle navigation based on the URL's state. This works well on mobile, but I noticed that the callback isn't firing when running the same code on the web using react-native-web.

Problem Description I want to navigate back to the home screen based on the URL loaded in the WebView. My current implementation uses onNavigationStateChange to check for specific keywords in the URL, but this approach does not seem to work on the web.

import React from 'react';
import { WebView } from 'react-native-webview';
import { useNavigation } from '@react-navigation/native';

const MyWebView = () => {
  const navigation = useNavigation();
  const redirectUrl = 'https://example.com';

  const handleNavigationStateChange = (newNavState) => {
    const { url } = newNavState;

    if (url && url.includes('success')) {
      navigation.getParent().goBack();
    } else if (url && url.includes('failure')) {
      navigation.goBack();
    }
  };

  return (
    <WebView
      source={{ uri: redirectUrl }}
      onNavigationStateChange={handleNavigationStateChange}
    />
  );
};

export default MyWebView;

Questions

  1. Why is onNavigationStateChange not firing on the web while it works perfectly on mobile?
  2. Are there any alternatives or best practices for handling URL changes in a WebView when running on the web?

Any insights or suggestions would be greatly appreciated!

Upvotes: 0

Views: 165

Answers (0)

Related Questions