Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Chrome window.onunload

I am developing an HTML5 app specifically for Android and Chrome. The problem I have stems from the requirement to track open browser tabs. I do this by creating a unique ID stored in each tab's sessionStorage. I then track the open tabs by registering each ID in a localStorage array that each tab has access to.

The problem is that I cannot remove the ID from localStorage when closing a tab by using the window.onunload event. The code works fine in desktop Chrome but I cannot get it working in Android.

$(window).on('beforeunload', function () {
    removeWindowGUID(); 
});

function removeWindowGUID() {
    var guid = sessionStorage.getItem("WindowGUID");
    var tmp = JSON.parse(localStorage.getItem("WindowGUIDs"));
    tmp = tmp.remove(guid);  // remove is a custom prototype fn
    localStorage.setItem("WindowGUIDs", JSON.stringify(tmp));
}

This event will fire when reloading a page, which is fine, just not on closing. I have also tried using the pagehide event.

like image 320
sreimer Avatar asked Jul 08 '13 20:07

sreimer


People also ask

What is window Onunload?

onunload occurs when the user navigates away from the page (by clicking on a link, submitting a form, closing the browser window, etc.). Note: The onunload event is also triggered when a user reloads the page (and the onload event).

What is the difference between Onbeforeunload and Onunload?

onbeforeunload Below are my findings on the iPad; Using window. onunload , I am able to get an alert when user navigates to a different page from myPage. html (either by clicking on some link or doing a Google search while on myPage.

What triggers Onbeforeunload?

The onbeforeunload event occurs when the document is about to be unloaded. This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page. The default message that appears in the confirmation box, is different in different browsers.

Does Beforeunload work on mobile?

according to the MDN docs, beforeunload and load events are supported since Chrome for Androied version 18 and Firefox for Android version 4. please provide the minimal portion of the related code so we can help you better.


1 Answers

Depends on the browser. Some use .onunload, some use onbeforeunload.

Quickest solution is

window.onunload = window.onbeforeunload = function() {
    var guid = sessionStorage.getItem("WindowGUID");
    var tmp = JSON.parse(localStorage.getItem("WindowGUIDs"));
    tmp = tmp.remove(guid);  // remove is a custom prototype fn
    localStorage.setItem("WindowGUIDs", JSON.stringify(tmp));
});

Tested on gingerbread, ICS & jelly bean using native android browser.

like image 169
Ohgodwhy Avatar answered Oct 21 '22 09:10

Ohgodwhy