简体   繁体   English

Android Chrome window.onunload

[英]Android Chrome window.onunload

I am developing an HTML5 app specifically for Android and Chrome .我正在开发一个专门为 Android 和 Chrome开发的 HTML5 应用程序。 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.为此,我创建了一个存储在每个选项卡的 sessionStorage 中的唯一 ID。 I then track the open tabs by registering each ID in a localStorage array that each tab has access to.然后我通过在每个选项卡可以访问的 localStorage 数组中注册每个 ID 来跟踪打开的选项卡。

The problem is that I cannot remove the ID from localStorage when closing a tab by using the window.onunload event.问题是在使用 window.onunload 事件关闭选项卡时,我无法从 localStorage 中删除 ID。 The code works fine in desktop Chrome but I cannot get it working in Android.该代码在桌面 Chrome 中运行良好,但我无法在 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.我也尝试过使用 pagehide 事件。

Depends on the browser.取决于浏览器。 Some use .onunload , some use onbeforeunload .有些使用.onunload ,有些使用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.使用原生安卓浏览器在姜饼、ICS 和果冻豆上进行测试。

I did something similar, the errors were exactly the same.我做了类似的事情,错误完全相同。 I noticed if call window.close() programmatically, the event is called.我注意到如果以编程方式调用 window.close() ,则会调用该事件。 I just added my own 'close' button on the page.我刚刚在页面上添加了我自己的“关闭”按钮。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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