Android Chrome window.onunload

回眸只為那壹抹淺笑 提交于 2019-12-30 08:41:50

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/17535076/android-chrome-window-onunload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!