flutter_inappwebview icon indicating copy to clipboard operation
flutter_inappwebview copied to clipboard

iOS Embeded Youtube Buffering Indefinitely with InterceptFetchRequest

Open getBoolean opened this issue 5 months ago • 3 comments

  • [x] I have read the Getting Started section
  • [x] I have already searched for the same problem

Environment

Technology Version
Flutter version 3.19.0-0.3.pre
Plugin version 6.0.0
Android version
iOS version 17.0/17.2
macOS version 14.0
Xcode version 15.2
Google Chrome version

Device information: iPad Pro 6th gen 12.9 inch

Description

Expected behavior: Embedded youtube video should play

Current behavior: Tested using holodex.net, embedded YouTube videos buffer indefinitely with useShouldInterceptFetchRequest set to true and with the InAppWebView.shouldInterceptFetchRequest function provided. It also happens with the shouldInterceptAjaxRequest function. For context, I need the ability to intercept and modify a request. This is only reproducible on iOS, not Android.

Steps to reproduce

Websites tested:

Click to see code
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:url_launcher/url_launcher.dart';

class WebView extends StatefulWidget {
  const WebView({super.key});

  @override
  State<WebView> createState() => _WebViewState();
}

class _WebViewState extends State<WebView> {
  final GlobalKey webViewKey = GlobalKey();

  InAppWebViewController? webViewController;
  InAppWebViewSettings settings = InAppWebViewSettings(
    isInspectable: kDebugMode,
    mediaPlaybackRequiresUserGesture: false,
    allowsInlineMediaPlayback: true,
    iframeAllow: 'camera; microphone',
    iframeAllowFullscreen: true,
    useShouldInterceptFetchRequest: true,
    userAgent:
        'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36',
  );

  PullToRefreshController? pullToRefreshController;
  String url = '';
  double progress = 0;
  final urlController = TextEditingController();

  @override
  void initState() {
    super.initState();

    pullToRefreshController = kIsWeb
        ? null
        : PullToRefreshController(
            settings: PullToRefreshSettings(
              color: Colors.blue,
            ),
            onRefresh: () async {
              if (defaultTargetPlatform == TargetPlatform.android) {
                await webViewController?.reload();
              } else if (defaultTargetPlatform == TargetPlatform.iOS) {
                await webViewController?.loadUrl(
                  urlRequest:
                      URLRequest(url: await webViewController?.getUrl()),
                );
              }
            },
          );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          children: <Widget>[
            _WebViewUrlBar(
              urlController: urlController,
              webViewController: webViewController,
            ),
            Expanded(
              child: Stack(
                children: [
                  InAppWebView(
                    key: webViewKey,
                    initialUrlRequest: URLRequest(
                      url: WebUri('https://holodex.net/'),
                    ),
                   gestureRecognizers:
                        <Factory<OneSequenceGestureRecognizer>>{}..add(
                            const Factory<VerticalDragGestureRecognizer>(
                              VerticalDragGestureRecognizer.new,
                            ),
                          ),
                    initialSettings: settings,
                    pullToRefreshController: pullToRefreshController,
                    onWebViewCreated: (controller) {
                      webViewController = controller;
                    },
                    onLoadStart: (controller, url) {
                      setState(() {
                        this.url = url.toString();
                        urlController.text = this.url;
                      });
                    },
                    onPermissionRequest: (controller, request) async {
                      return PermissionResponse(
                        resources: request.resources,
                        action: PermissionResponseAction.GRANT,
                      );
                    },
                    // shouldInterceptAjaxRequest:
                    //     (controller, ajaxRequest) async {
                    //   print(ajaxRequest.url);
                    //   return ajaxRequest;
                    // },
                    // ----------- PROBLEM
                    // even though this just returns the same request, the video keeps buffering
                    shouldInterceptFetchRequest:
                        (controller, fetchRequest) async => fetchRequest,
                    shouldOverrideUrlLoading:
                        (controller, navigationAction) async {
                      final uri = navigationAction.request.url;
                      if (uri == null) {
                        return NavigationActionPolicy.ALLOW;
                      }

                      if (![
                        'http',
                        'https',
                        'file',
                        'chrome',
                        'data',
                        'javascript',
                        'about',
                      ].contains(uri.scheme)) {
                        if (await canLaunchUrl(uri)) {
                          // Launch the App
                          await launchUrl(
                            uri,
                          );
                          // and cancel the request

                          return NavigationActionPolicy.CANCEL;
                        }
                      }

                      return NavigationActionPolicy.ALLOW;
                    },
                    onLoadStop: (controller, url) async {
                      await pullToRefreshController?.endRefreshing();
                      setState(() {
                        this.url = url.toString();
                        urlController.text = this.url;
                      });
                    },
                    onReceivedError: (controller, request, error) {
                      pullToRefreshController?.endRefreshing();
                    },
                    onProgressChanged: (controller, progress) {
                      if (progress == 100) {
                        pullToRefreshController?.endRefreshing();
                      }
                      setState(() {
                        this.progress = progress / 100;
                        urlController.text = url;
                      });
                    },
                    onUpdateVisitedHistory: (controller, url, androidIsReload) {
                      setState(() {
                        this.url = url.toString();
                        urlController.text = this.url;
                      });
                    },
                    onConsoleMessage: (controller, consoleMessage) {
                      if (kDebugMode) {
                        print(consoleMessage);
                      }
                    },
                  ),
                  if (progress < 1.0)
                    LinearProgressIndicator(value: progress)
                  else
                    Container(),
                ],
              ),
            ),
            _WebViewControls(webViewController: webViewController),
          ],
        ),
      ),
    );
  }
}

class _WebViewControls extends StatelessWidget {
  const _WebViewControls({
    required this.webViewController,
  });

  final InAppWebViewController? webViewController;

  @override
  Widget build(BuildContext context) {
    return ButtonBar(
      alignment: MainAxisAlignment.center,
      children: <Widget>[
        ElevatedButton(
          child: const Icon(Icons.arrow_back),
          onPressed: () {
            webViewController?.goBack();
          },
        ),
        ElevatedButton(
          child: const Icon(Icons.arrow_forward),
          onPressed: () {
            webViewController?.goForward();
          },
        ),
        ElevatedButton(
          child: const Icon(Icons.refresh),
          onPressed: () {
            webViewController?.reload();
          },
        ),
      ],
    );
  }
}

class _WebViewUrlBar extends StatelessWidget {
  const _WebViewUrlBar({
    required this.urlController,
    required this.webViewController,
  });

  final TextEditingController urlController;
  final InAppWebViewController? webViewController;

  @override
  Widget build(BuildContext context) {
    return TextField(
      decoration: const InputDecoration(prefixIcon: Icon(Icons.search)),
      controller: urlController,
      keyboardType: TextInputType.url,
      onSubmitted: loadUrl,
      onTapOutside: (event) {
        loadUrl(urlController.text);
      },
    );
  }

  void loadUrl(String value) {
    var url = WebUri(value);
    if (url.scheme.isEmpty) {
      url = WebUri('https://www.google.com/search?q=$value');
    }
    webViewController?.loadUrl(
      urlRequest: URLRequest(url: url),
    );
  }
}

Images

Stacktrace/Logcat

getBoolean avatar Jan 29 '24 04:01 getBoolean

👋 @getBoolean

NOTE: This comment is auto-generated.

Are you sure you have already searched for the same problem?

Some people open new issues but they didn't search for something similar or for the same issue. Please, search for it using the GitHub issue search box or on the official inappwebview.dev website, or, also, using Google, StackOverflow, etc. before posting a new one. You may already find an answer to your problem!

If this is really a new issue, then thank you for raising it. I will investigate it and get back to you as soon as possible. Please, make sure you have given me as much context as possible! Also, if you didn't already, post a code example that can replicate this issue.

In the meantime, you can already search for some possible solutions online! Because this plugin uses native WebView, you can search online for the same issue adding android WebView [MY ERROR HERE] or ios WKWebView [MY ERROR HERE] keywords.

Following these steps can save you, me, and other people a lot of time, thanks!

github-actions[bot] avatar Jan 29 '24 04:01 github-actions[bot]

Looks like shouldInterceptFetchRequest won't do what I want anyway (intercept the url given to an iframe). I'll keep this open since its a weird edge case.

getBoolean avatar Jan 30 '24 07:01 getBoolean

Hey, I had the same issue with embedded YT videos. I solved it by injecting a JS detecting the videos and displaying buttons which after clicking them would open ChromeSafariBrowser with YT URL.

It seems this is some iOS blockade. I had the same issue with embedded PowerPoint

SkepsonSk avatar Mar 23 '24 08:03 SkepsonSk