7

当用户单击 webview 中存在的按钮时,我想在我的 Flutter 应用程序中关闭 webview

这是显示网络视图的代码

class WebViewApp extends StatefulWidget {
  @override
  _WebViewAppState createState() => _WebViewAppState();
}

class _WebViewAppState extends State<WebViewApp> {
  @override
  Widget build(BuildContext context) {
    return  WebviewScaffold(url: 'https://google.com',
        appBar: AppBar(
          title: Text('Test'),
          centerTitle: true,
          backgroundColor: kBlue,
          leading: BackButton(
            onPressed: (){
              Router.navigator.pop();
            },
          )
        ),
      );
  }
}

示例图像,我想检测运动是否

4

3 回答 3

10

单击 WebView 中的按钮时,请检查以下步骤以获取触发器:

  • 添加 webview 插件

    webview_flutter: ^0.3.22+1

  • pubspec.yaml

     assets:   
        assets/about_us.html
    
  • 在 assets 文件夹中添加了 html 文件

about_us.html

<html>

<head>
    <script type="text/javascript">
        function invokeNative() {
            MessageInvoker.postMessage('Trigger from Javascript code');
        }
    </script> </head>

<body>
    <form>
        <input type="button" value="Click me!" onclick="invokeNative()" />
    </form> </body>

</html>
  • 添加了加载 WebView 的代码。

根据以下语句,您可以看到我正在加载一个 WebView,当我单击名为Click me!的按钮时 在 WebView 中,flutter 中的 JavascriptChannel 将被调用,并显示一条消息“来自 Javascript 代码的触发器”

import 'dart:convert';
import 'package:flutter/material.dart'; 
import 'package:flutter/services.dart'; 
import 'package:webview_flutter/webview_flutter.dart';

class WebViewApp extends StatefulWidget {
  WebViewApp({Key key, this.title}) : super(key: key);
  final String title;
  @override
  _WebViewAppState createState() => _WebViewAppState();
}

class _WebViewAppState extends State<WebViewApp> {
  WebViewController _controller;
  Future<void> loadHtmlFromAssets(String filename, controller) async {
    String fileText = await rootBundle.loadString(filename);
    controller.loadUrl(Uri.dataFromString(fileText,
            mimeType: 'text/html', encoding: Encoding.getByName('utf-8'))
        .toString());
  }
  Future<String> loadLocal() async {
    return await rootBundle.loadString('assets/about_us.html');
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: FutureBuilder<String>(
        future: loadLocal(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            return WebView(
              initialUrl:
                  new Uri.dataFromString(snapshot.data, mimeType: 'text/html')
                      .toString(),
              javascriptMode: JavascriptMode.unrestricted,
              javascriptChannels: <JavascriptChannel>[
                JavascriptChannel(
                    name: 'MessageInvoker',
                    onMessageReceived: (s) {
                    Scaffold.of(context).showSnackBar(SnackBar(
                       content: Text(s.message),
                    ));
                    }),
              ].toSet(),
            );
          } else if (snapshot.hasError) {
            return Text("${snapshot.error}");
          }
          return CircularProgressIndicator();
        },
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

正如您在代码中看到的,JavascriptChannel当用户单击 webview 中的按钮时,将调用一个。有一个密钥可以识别频道,在我的情况下是MessageInvoker.

希望这能解决问题... 在此处输入图像描述

于 2020-08-01T19:46:55.610 回答
6

WebView您可以通过检查 url即将打开来收听点击:

WebView(
  initialUrl: 'https://google.com',
  navigationDelegate: (request) {
    if (request.url.contains('mail.google.com')) {
      print('Trying to open Gmail');
      Navigator.pop(context); // Close current window
      return NavigationDecision.prevent; // Prevent opening url
    } else if (request.url.contains('youtube.com')) {
      print('Trying to open Youtube');
      return NavigationDecision.navigate; // Allow opening url
    } else {
      return NavigationDecision.navigate; // Default decision
    }
  },
),
于 2021-06-23T17:40:02.387 回答
0

在 Webview 构造函数中使用navigationDelegate参数。

WebView(
  initialUrl: 'https://flutter.dev',
  navigationDelegate: (action) {
    if (action.url.contains('google.com')) {
      // Won't redirect url
      print('Trying to open google');
      Navigator.pop(context); 
      return NavigationDecision.prevent; 
    } else if (action.url.contains('youtube.com')) {
     // Allow opening url
      print('Trying to open Youtube');
      return NavigationDecision.navigate; 
    } else {
      return NavigationDecision.navigate; 
    }
  },
),

而已!

于 2021-07-29T13:59:17.780 回答