How to disable navigation away from initial URL in Flutter Webview

Viewed 432

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.

1 Answers

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.

Related