简体   繁体   中英

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.

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.

I did something similar, the errors were exactly the same. I noticed if call window.close() programmatically, the event is called. I just added my own 'close' button on the page.

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