6

I would like to indicate to the user that there's a file being downloaded when they try to close the tab in my flutter web app. Is there a way of hooking into the app to detect this behavior and to show such a warning message?

Warning popup

moazelshebly
  • 145
  • 9
  • There's a similar question to this, refer to: https://stackoverflow.com/questions/62237262/flutter-web-detect-browser-tab-close-or-refresh – neil_ruaro Apr 19 '21 at 12:23
  • There's a similar question to this, refer to: https://stackoverflow.com/questions/62237262/flutter-web-detect-browser-tab-close-or-refresh – neil_ruaro Apr 19 '21 at 12:24
  • 2
    This is not really the same question. I know you can subscribe to reload and close events but you can't really show anything in your window when these events happen – moazelshebly Apr 19 '21 at 14:01

1 Answers1

5

You may register code for a BeforeUnloadEvent like this:

import 'dart:html' as html;

/// Subscription on application termination warning
StreamSubscription? _onBeforeUnloadSubscription;

//enable warning for closing browser tab:
_onBeforeUnloadSubscription = registerOnBeforeUnload("Transfers in progress!");

//disable warning for closing browser tab:
stopBeforeUnloadHandler();


StreamSubscription? registerOnBeforeUnload(String warningMessage) {
  StreamSubscription<html.BeforeUnloadEvent> _onBeforeUnloadSubscription;

  _onBeforeUnloadSubscription = html.window.onBeforeUnload.listen((e) async {
    (e as html.BeforeUnloadEvent).returnValue = warningMessage;
    return Future.value(warningMessage);
  }) as StreamSubscription<html.BeforeUnloadEvent>;
  return _onBeforeUnloadSubscription;
}

void stopBeforeUnloadHandler() {
  if (_onBeforeUnloadSubscription != null) {
    _onBeforeUnloadSubscription!.cancel();
    _onBeforeUnloadSubscription = null;
  }
}
technolion
  • 83
  • 1
  • 5