简体   繁体   中英

How to detect closing of mobile browser (Android Chrome) with 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM