在Android上将页面留在后台时触发"beforeunload"事件 [英] 'beforeunload' event triggers when page is left in the background on Android

查看:299
本文介绍了在Android上将页面留在后台时触发"beforeunload"事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个简单的加载微调器,该微调器在导航时会弹出.导航时,它使用'beforeunload'事件显示,并在完成后使用'load'事件再次隐藏自身.

I'm trying to make a simple loading spinner that pops up when navigating. It shows up using a 'beforeunload' event when navigating away and uses the 'load' event to hide itself again when it is done.

问题是,当我将页面留在手机的后台时,例如几个小时后,"beforeunload"事件将触发并显示微调框.可能是因为Android上的Chrome浏览器部分卸载了页面以节省内存.旋转器本身并不会自动消失,而且我似乎无法弄清楚如何使其以优雅的方式再次消失.

The problem is that when I leave the page in the background on my phone for e.g. a few hours the 'beforeunload' event triggers and displays the spinner. Probably because Chrome on Android is partially unloading the page to save memory. The spinner doesn't go away by itself though and I can't seem to figure out how to make it disappear again in an elegant way.

还有其他我应该使用的事件吗?

Is there any other event I should be using instead?

    window.addEventListener("load", function() {
        topSpinner.classList.add("closed");
    });

    window.addEventListener("beforeunload", function() {
        topSpinner.classList.remove("closed");
    });

推荐答案

Chrome 68(2018年7月)引入了新的

Chrome 68 (July 2018) introduced a new Page Lifecycle API: the state diagram supplied in this link does not show the System (browser) calling beforeunload before putting the page into the frozen state, but that is clearly what is happening.

有帮助的是,API引入了两个新事件,它们在页面进入和退出此状态时触发:freezeresume.

Helpfully, the API introduced two new events that trigger as the page enters and exits this state: freeze and resume.

通过添加以下内容,我已经解决了移动chrome和webview显示器上的此问题:

I've solved this problem on both mobile chrome and webview displays simply by adding this:

document.addEventListener('resume', (event) => {
  // The page has been unfrozen: remove the spinner if it's active
 topSpinner.classList.add("closed");
});

这篇关于在Android上将页面留在后台时触发"beforeunload"事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆