【问题标题】:How do I open multiple WebViews on flutter?如何在颤振上打开多个 WebView?
【发布时间】:2019-11-25 18:25:42
【问题描述】:

我有一个简单的 Flutter WebView 应用程序来显示我的网站。 问题是,在我的网站中,我有 2 个功能可以打开一个新的浏览器窗口。

例如,其中一个是facebook登录功能,当用户点击用facebook登录时,它会加载facebook登录api页面,当登录完成时,它会告诉用户返回另一个页面,但是因为我在 WebView 中,所以我无法返回到其他页面。

有什么方法可以让我在 Flutter 上打开 2 个 WebView 来加载不同的页面吗?如果没有,这个问题还有其他可能的解决方案吗?

【问题讨论】:

    标签: flutter webview


    【解决方案1】:

    webview_flutter 插件不提供在新窗口打开时管理和拦截的事件,例如,当您单击带有 target="_blank" 的链接按钮或 JavaScript 端调用 window.open() 时。

    所以,你可以使用我的插件flutter_inappwebview,这是一个 Flutter 插件,可以让你添加内联 WebViews 或打开应用内浏览器窗口,并且有很多事件、方法和选项来控制 WebViews。

    它实现了onCreateWindow 事件,这是当 WebView 请求宿主应用程序创建新窗口时触发的事件,例如,当尝试使用 target="_blank" 打开链接或当 JavaScript 调用 window.open() 时一边。

    这是一个示例,其中我加载了一个简单的初始 HTML(只是为了示例),它有一个按钮 <button id="login-button">LOGIN</button>,当它被点击时,它会在 AlertDialog 中打开一个新的 WebView。使用这个新的 WebView,您可以通过 onLoadStop 事件或使用 shouldOverrideUrlLoading 事件来监听 URL 更改,或者您可以在用户登录后检查并获取特定的 cookie。您可以在这个新的 WebView 中放置任何逻辑。

    下面是代码示例:

    import 'dart:async';
    import 'package:flutter/material.dart';
    import 'package:flutter_inappwebview/flutter_inappwebview.dart';
    
    Future main() async {
      WidgetsFlutterBinding.ensureInitialized();
      runApp(MyApp());
    }
    
    class MyApp extends StatefulWidget {
      @override
      _MyAppState createState() => new _MyAppState();
    }
    
    class _MyAppState extends State<MyApp> {
      @override
      void initState() {
        super.initState();
      }
    
      @override
      void dispose() {
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(initialRoute: '/', routes: {
          '/': (context) => InAppWebViewExampleScreen(),
        });
      }
    }
    
    class InAppWebViewExampleScreen extends StatefulWidget {
      @override
      _InAppWebViewExampleScreenState createState() =>
          new _InAppWebViewExampleScreenState();
    }
    
    class _InAppWebViewExampleScreenState extends State<InAppWebViewExampleScreen> {
      InAppWebViewController _webViewController;
      CookieManager _cookieManager = CookieManager.instance();
    
      @override
      void initState() {
        super.initState();
      }
    
      @override
      void dispose() {
        super.dispose();
      }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(title: Text("InAppWebView")),
            body: Container(
                child: Column(children: <Widget>[
              Expanded(
                  child: InAppWebView(
                initialData: InAppWebViewInitialData(data: """
    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
            <meta http-equiv="X-UA-Compatible" content="ie=edge">
            <title>InAppWebViewInitialDataTest</title>
        </head>
        <body>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi dolor diam, interdum vitae pellentesque sit amet, scelerisque at magna. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.</p>
            <p>Nullam vitae fringilla mauris, eu efficitur erat. Nulla aliquam ligula nec leo ornare varius. Curabitur ornare ultrices convallis.</p>
            <button id="login-button">LOGIN</button>
            <script>
              document.querySelector('#login-button').addEventListener('click', function (event) {
                window.open('https://github.com/', '_blank');
              });
            </script>
        </body>
    </html>
                        """),
                initialHeaders: {},
                initialOptions: InAppWebViewGroupOptions(
                    crossPlatform: InAppWebViewOptions(
                      debuggingEnabled: true,
                    ),
                    android:
                        AndroidInAppWebViewOptions(supportMultipleWindows: true)),
                onWebViewCreated: (InAppWebViewController controller) {
                  _webViewController = controller;
                },
                onLoadStart: (InAppWebViewController controller, String url) {
    
                },
                onLoadStop: (InAppWebViewController controller, String url) {
    
                },
                onCreateWindow: (controller, onCreateWindowRequest) {
                  showDialog(
                    context: context,
                    builder: (context) {
                      return AlertDialog(
                          content: Container(
                              width: 700,
                              child: Column(children: <Widget>[
                                Expanded(
                                    child: InAppWebView(
                                  initialUrl: onCreateWindowRequest.url,
                                  initialOptions: InAppWebViewGroupOptions(
                                      crossPlatform: InAppWebViewOptions(
                                          debuggingEnabled: true,
                                          useShouldOverrideUrlLoading: true)),
                                  onLoadStart: (InAppWebViewController controller,
                                      String url) {},
                                  onLoadStop: (controller, url) async {
                                    print(url);
                                    if (url == "myURL") {
                                      Navigator.pop(context);
                                      return;
                                    }
    
                                    var loggedInCookie = await _cookieManager.getCookie(url: url, name: "logged_in");
                                    if (loggedInCookie.value == "yes") {
                                      Navigator.pop(context);
                                      return;
                                    }
                                  },
                                  shouldOverrideUrlLoading: (controller,
                                      shouldOverrideUrlLoadingRequest) async {
                                    print(shouldOverrideUrlLoadingRequest.url);
                                    if (shouldOverrideUrlLoadingRequest.url == "myURL") {
                                      Navigator.pop(context);
                                    }
                                    return ShouldOverrideUrlLoadingAction.ALLOW;
                                  },
                                ))
                              ])));
                    },
                  );
                },
              ))
            ])));
      }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-13
      • 2020-04-02
      • 1970-01-01
      • 2020-11-10
      • 2022-07-04
      • 2021-07-28
      • 2019-04-17
      • 2019-07-06
      相关资源
      最近更新 更多