Getting the Current URL in Flutter using WebView

The WebView widget in Flutter allows you to display web content in your app. It provides a full-featured web browser that can handle complex web pages.

Sometimes you may need to get the current URL that is loaded in the WebView. This can be useful for tracking page navigation, analytics, saving state, etc.

Flutter makes it easy to get the current URL through the WebViewController. Here are some common ways to get the URL:

[/su_box]

Using webView.currentUrl()

The simplest way is to call webView.currentUrl() on the WebViewController. This will return the URL as a string:

String url = webViewController.currentUrl();

This can be called at any time to get the latest URL.

Listening to onWebViewCreated()

You can listen to the onWebViewCreated callback and subscribe to url changes:

final webViewController = WebViewController()
  ..onWebViewCreated = (controller) {
    controller.url.listen((url) {
      // New url loaded
    });
  }

This will fire whenever the active URL changes in the WebView.

This shows getting the URL at various points using the WebViewController callbacks.

Listening to onPageStarted()

Another option is to subscribe to the onPageStarted callback:

webViewController.onPageStarted.listen((url) {
  // New page loaded
});

This fires at the start of each new page load.

Listening to onPageFinished()

You can also use onPageFinished to get the URL after a page completes loading:

webViewController.onPageFinished.listen((url) {
  // Page finished loading
});

This will return the final resolved URL after all redirects.

Handling Custom URL Schemes

If you have custom URL schemes registered for your app, you can listen for those as well:

webViewControll.onUrlChanged.listen((Uri uri) {
  if (uri.scheme == 'customscheme') {
    // Handle custom scheme
  }
});

This allows you to respond to custom URLs that you navigate to internally within the WebView.

Getting the URL on Navigation

You can get the URL at the start of any navigation by listening to onNavigationRequest:

webView.onNavigationRequest.listen((req) {
  var url = req.url;
});

This fires for every top-level navigation request.

When to Get the Current URL

Some common cases where getting the current WebView URL is useful:

  • Saving and restoring state of WebView
  • Intercepting and handling custom internal URLs
  • Tracking page analytics
  • Integrating with other services that need current web page
  • Debugging page issues and logs
  • Passing URL to native side for further processing
  • Grabbing title or metadata from URLs

So in summary, Flutter provides flexible options for getting the current URL through:

  • webView.currentUrl() – get latest URL at any time
  • onWebViewCreated – subscribe to URL changes
  • onPageStarted – URL at start of new loads
  • onPageFinished – final URL after redirects
  • onNavigationRequest – URL for each new navigation

Example Flutter Code

Here is some example Dart code for getting the current WebView URL at different points:

// Import WebView plugin
import 'package:webview_flutter/webview_flutter.dart';

class WebViewExample extends StatefulWidget {

  @override
  _WebViewExampleState createState() => _WebViewExampleState();
}

class _WebViewExampleState extends State<WebViewExample> {

  final webViewController = WebViewController();  

  @override
  void initState() {
    super.initState();
    
    // Subscribe to onWebViewCreated
    webViewController.onWebViewCreated = (controller) {

      // Get initial URL
      String url = controller.currentUrl();  

      // Subscribe to URL changes
      controller.url.listen((url) {
        // New URL loaded
      });
    }

    // Listen for page loads
    webViewController.onPageStarted.listen((url) {
      // Page load started
    });

    webViewController.onPageFinished.listen((url) {
      // Page finished loading
    });

    // Handle navigation requests
    webViewController.onNavigationRequest.listen((request) {
      var url = request.url; 
    });
  }

  @override
  Widget build(BuildContext context) {

    return WebViewWidget(
      controller: webViewController,
    );
  }
}

This shows getting the URL at various points using the WebViewController callbacks.

Common Issues

Here are some common issues faced when getting the current URL:

  • Forgetting to call await webView.currentUrl() – need to await async call
  • Calling currentUrl() before navigation starts
  • Not accounting for automatic redirects
  • Not properly encoding/decoding URL
  • Making sure to handle both HTTP and HTTPS
  • Getting relative URL instead of fully qualified URL
    -Receiving about:blank initial URL before navigation

So be sure to handle async execution, wait for navigation to start, account for redirects, and handle URL encoding properly.

FAQs

Some frequently asked questions about getting the current WebView URL in Flutter:

Q: How do I get the URL every time it changes?

Subscribe to the url stream on the WebViewController to listen for all URL changes.

Q: When does onPageStarted and onPageFinished fire?

onPageStarted fires when the initial request is made for a new page. onPageFinished fires once the full page including subresources has completed loading.

Q: Can I manipulate the URL programmatically?

Yes, you can call methods like goBack(), goForward(), reload() on the WebViewController to change the active URL.

Q: How do I handle REST calls from JavaScript?

Use onUrlChanged to intercept custom REST API calls from JavaScript and pass to native Dart code.

Q: Is the URL always fully qualified?

Generally the URL will be fully qualified including the scheme and domain. But sometimes you may get partial relative URLs depending on context.

Q: What are some use cases for getting the URL?

  • Saving/restoring WebView state
  • Tracking page analytics
  • Passing URL to native side for processing
  • Handling custom URL schemes
  • Intercepting page calls to APIs

Summary

  • Use webView.currentUrl() to get current URL at any time
  • Listen to onWebViewCreated, onPageStarted, onPageFinished for URL changes
  • Handle navigation requests and custom schemes
  • Account for async execution, redirects, and encoding
  • Access URL to save state, intercept API calls, and more

Getting the current URL of a WebView is easy in Flutter thanks to the helpful callbacks and API of the WebView plugin. With a few lines of code, you can monitor the current page URL and respond accordingly in your app.

Leave a Comment