How to get current URL with React Native webview?

Sometimes, we want to get current URL with React Native webview.

In this article, we’ll look at how to get current URL with React Native webview.

How to get current URL with React Native webview?

To get current URL with React Native webview, we can set the onNavigationStateChange prop to a function that listens for navigation events in the webview.

For instance, we write:

import * as React from 'react';
import { View } from 'react-native';
import Constants from 'expo-constants';
import { Card } from 'react-native-paper';
import { WebView } from 'react-native-webview';

export default function App() {
  const onNavigationStateChange = (webViewState) => {
    console.log(webViewState.url);
  };

  return (
    <View style={{ flex: 1 }}>
      <WebView
        source={{ uri: 'https://example.com' }}
        onNavigationStateChange={onNavigationStateChange}
        javaScriptEnabled
        domStorageEnabled
        startInLoadingState={false}
      />
    </View>
  );
}

to set onNavigationStateChange to the onNavigationStateChange function.

In it, we log webViewState.url which has the URL of the current page in the webview.

Conclusion

To get current URL with React Native webview, we can set the onNavigationStateChange prop to a function that listens for navigation events in the webview.