Reputation: 557
I have a Flutter app that loads a web site into a WebView widget.
Is there any way to lock that webview to the initial website? I don't want the user to be able to navigate away from this page.
Upvotes: 6
Views: 3958
Reputation: 4437
You can also do something like:
onNavigationRequest: (navigation) {
if (navigation.url != 'https://flutter.dev') {
return NavigationDecision.prevent;
}
return NavigationDecision.navigate;
},
or if you want to allow navigation in domain only:
onNavigationRequest: (navigation) {
if (!navigation.url.startsWith('https://flutter.dev')) {
return NavigationDecision.prevent;
}
return NavigationDecision.navigate;
},
Full code:
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';
void main() {
runApp(
const MaterialApp(
home: WebViewApp(),
),
);
}
class WebViewApp extends StatefulWidget {
const WebViewApp({super.key});
@override
State<WebViewApp> createState() => _WebViewAppState();
}
class _WebViewAppState extends State<WebViewApp> {
late final WebViewController controller;
String url = 'https://flutter.dev';
@override
void initState() {
controller = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setNavigationDelegate(
NavigationDelegate(
onNavigationRequest: (navigation) {
if (navigation.url != url) {
return NavigationDecision.prevent;
}
return NavigationDecision.navigate;
},
),
)
..loadRequest(Uri.parse(url));
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter WebView'),
),
body: WebViewWidget(
controller: controller,
),
);
}
}
Upvotes: 1
Reputation: 1683
In a StatefullWidget
you can put this line of code:
The navigationDelegate
plays the key role in this scenario.
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter Web View'),
backgroundColor: AppColors.engenesisBlue,
),
body: WebView(
initialUrl: widget.url,
javascriptMode: JavascriptMode.unrestricted,
navigationDelegate: (NavigationRequest request) {
print(request.url);
setState(() => counter++);
if (counter == 1) {
return NavigationDecision.navigate;
}
return NavigationDecision.prevent;
},
),
);
}
The web view will refuse to navigate twice. Therefore you cannot navigate once the page loaded.
Upvotes: 4