Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect closing of mobile browser (Android Chrome) with Javascript?

Tags:

javascript

we are trying to get some thorough data on our users' activity, so we are building ourselves a library, that logs time users spend on given page. We are measuring times using TimeMe library. We are trying to send the measurments to our server only once, when user change page, quit tab, close browser etc.

Currently we are listening to two events:

  1. page:before-unload on document (because of rails' turbolinks)
  2. beforeunload on window (other cases)

It works just fine on desktop browsers. However these listeners won't catch some events. For example if we visit the site on mobile browser (Android Chrome) and then close this browser, these listeners won't fire.

My question is, how can we fix this? What event do mobile browser create, when they are being closed?

Thank you for your advice.

like image 705
piko Avatar asked Nov 10 '22 12:11

piko


1 Answers

You can never detect the closing of browser by JavaScript, JavaScript is a Dynamically typed language and it uses browser engines to execute. But if you are going to close browser then how can the JavaScript code will be able to execute. So, this is not possible at all. but in cases to deal with google chrome, since android is an operating system and supports javascript compilation, because V8 is also the execution engine for chrome provided by google. So the following script might lead to a right track.

$(window).bind('beforeunload', function() {
if (iWantTo) {
return "Don't leave me!";
}
});

Blockquote
like image 86
Abhishek sharma Avatar answered Nov 14 '22 21:11

Abhishek sharma