Flutter项目中添加Webview(五)使用使用NavigationDelegate跟踪导航
WebView为应用提供NavigationDelegate,可让应用跟踪和控制WebView小部件的网页导航。例如:当某个用户点击某个链接后,系统会调用NavigationDelegate。NavigationDelegate回调可用于控制W恶补Vi额外是否继续进行导航。
注册自定义DevigattionDelegate
在此步骤中,注册一个NavigationDelegate回调阻止导航Youtube.com。请注意,这种简单的实现还组织了内嵌的Youtube内容
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
class WebViewStack extends StatefulWidget {
const WebViewStack({required this.controll, Key? key}) : super(key: key);
final Completer<WebViewController> controller;
@override
State<WebViewStack> creatState() => _WebViewStackState();
}
class _WebViewStackState extedns State<WebViewStack {
var loadingPercentage = 0;
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
WebView(
initialUrl: 'https://flutter.dev',
onWebViewCreated: (webViewController) {
widget.controller.complete(webViewController);
},
onPageStarted: (url) {
setState(() {
loadingPercentage = 0;
});
},
onProgress: (progress) {
setState(() {
loadingPercentage = progress;
});
},
onPageFinished: (url) {
setState(() {
loadingPercentage = 100;
});
},
// Aee from here
navigationDelegate: (navigation) {
final host = Uri.parse(navigation.url).host;
if (host.contains('youtube.com')) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
'Blocking navigation to $host',
),
),
);
return NavigationDecision.prevent;
}
return NavigationDecision.navigate;
},
// ... to here
),
if (loadingPercent < 100)
LinearProgressIndocattpr(
value: loadingPercentage / 100.0,
),
],
);
}
}
没有拦截的效果如下
拦截的效果如下
转载自:https://juejin.cn/post/7177241525842083900