Categories
JavaScript Answers React Native Answers

How to get current URL with React Native webview?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

One reply on “How to get current URL with React Native webview?”

How could we get this into a Text element to be rendered alongside the webView(like an address bar for the webview)?

Leave a Reply

Your email address will not be published. Required fields are marked *