Search code examples
flutterflutter-dependenciesflutterwebviewplugin

How should I be using the Flutter Webview delegate methods to be able get request data


I'm using a webview in Flutter and struggling to view the headers of a url request. Looking at the webview_flutter documentation the headers appear to be available via the WebViewRequest class but i'm not seeing that come through any delegate methods. Based upon the request URL i'd like to look at the headers and based on the URL and header combination perform specific actions within my app.

I've implemented the webview controller and am not seeing the WebViewRequest as a property that is available in any of the delegate methods.

My webview implementation for reference:

child: WebView(
  initialUrl: null,
  javascriptMode: JavascriptMode.unrestricted,
  onWebViewCreated: (WebViewController w) {
    _webViewController = w;
    _webViewController.loadUrl(loginRequestUrl);
  },
  navigationDelegate: this._interceptNavigation,
  onPageStarted: (url) {
    // If URL is <login redirect URL> Check headers for success callback
    // If we have success, call mobile API with token and close webview
    print('Started Loading URL:');
    print(url);
  },
  onPageFinished: (finish) {
    // Reading response on finish
    // If URL is <authenticated in app url> we've missed the success callback and webview is loading web-facing product
    print('Finished Loading URL:');
    print(finish);
  },
),

Solution

  • You can use InAppWebView instead like this:

    InAppWebView(
              initialUrlRequest:
                  URLRequest(url: Uri.parse("https://stackoverflow.com")),
              initialOptions: InAppWebViewGroupOptions(
                crossPlatform:
                    InAppWebViewOptions(useShouldOverrideUrlLoading: true),
                android: AndroidInAppWebViewOptions(
                  useHybridComposition: true,
                ),
              ),
              shouldOverrideUrlLoading: (controller, navigationAction) async {
                var request = navigationAction.request;
                var url = request.url;
    
                if (request.headers != null) {
                  print('see header');
                  return NavigationActionPolicy.ALLOW;
                }
                return NavigationActionPolicy.ALLOW;
              },
            )