Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter Web: Detect browser/tab close or refresh?

With Flutter Android and iOS modules you can use AppLifeCycleState to detect when the app is put into the background.

Is there something similar for Flutter Web where I can detect the browser/tab closing or refreshing?

I essentially want to run a Firestore command if the person closes their browser or refreshes.

like image 282
Ross Patterson Avatar asked Jun 06 '20 19:06

Ross Patterson


People also ask

What happens when you refresh the page in flutter?

When you refresh the page, the entire app is destroyed and launched again. This is how the browser works, nothing specific to Flutter here. So the values of local variables are expected to disappear. The way navigation works today is by keeping the navigation stack in memory.

How to detect the closing of a browser tab?

How to Detect the Closing of a Browser Tab. 1 If navigation entries have reload navigation type, the user reloaded the page. 2 If the tab count is decreased, the user closed a tab. 3 If the tab count is decreased AND the storage time difference is less than 50ms, the user probably closed the browser.

How do I understand a browser Close event?

To understand a browser close, we need to first understand how a browser is closed. When a user closes the browser window, each tab within that browser is closed one after the other (based on my experiments, the delay in Chrome is about 1 ms on light to average load). Now, we know that a browser close will trigger beforeunload event handler.

Can I control when user will refresh the web page and close?

You cannot control when user will refresh the web page and close it, but it’s important sometimes to display a confirmation alert before closing the Tab. The user may be mistakenly clicked the close button and lost some important data.


2 Answers

You can use the function "onBeforeUnload" to check if the tab is being closed. It might detect page refresh also.

import 'dart:html' as html;
html.window.onBeforeUnload.listen((event) async{
  // do something
});

or

import 'dart:html' as html;
html.window.onUnload.listen((event) async{
  // do something
});
like image 187
Bharath Avatar answered Sep 23 '22 18:09

Bharath


Just use OnBeforeUnload or OnUnload. to me it worked without async, I recon it is because the window doesn't wait to be closed it just closes. if you want to change something in your db when the user exits tab or refreshes, you should call a method on the back thread so that it will keep on running and finish the task even after window closed/tab closed/refresh.

html.window.onBeforeUnload.listen((event) {
   // change something in db
});
like image 25
Micky Kroitoro Avatar answered Sep 24 '22 18:09

Micky Kroitoro