当用户从其他选项卡返回时重新加载页面 [英] Reload page when user returns from other tab

查看:30
本文介绍了当用户从其他选项卡返回时重新加载页面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在某类网站上工作,该网站重视及时更新.为此,当用户从另一个选项卡切换到该网站的选项卡时,我需要刷新页面.

I work on some kind of website that places importance on being up-to-date. For that purpose, I need to refresh the page when the user switches from another tab to the tab with the website.

有没有办法用 JavaScript/jQuery 做到这一点?我知道 location.reload(); 用于刷新页面,但我不知道如何在选项卡再次变为活动状态时告诉 JavaScript 执行此操作(并且只有一次).

Is there a way to do this with JavaScript / jQuery? I know that location.reload(); is used to refresh a page, but I don't know how to tell JavaScript to do this when the tab becomes active again (and only once then).

推荐答案

你可以使用这个:

var vis = (function(){
var stateKey, eventKey, keys = {
    hidden: "visibilitychange",
    webkitHidden: "webkitvisibilitychange",
    mozHidden: "mozvisibilitychange",
    msHidden: "msvisibilitychange"
};
for (stateKey in keys) {
    if (stateKey in document) {
        eventKey = keys[stateKey];
        break;
    }
}
return function(c) {
    if (c) document.addEventListener(eventKey, c);
    return !document[stateKey];
}
})();

用法:

var visible = vis(); // gives current state

vis(aFunction);      // registers a handler for visibility changes`

vis(function(){
    document.title = vis() ? 'Visible' : 'Not visible';
});

你可以在这里阅读:

检测浏览器选项卡是否处于活动状态或用户已离开

这篇关于当用户从其他选项卡返回时重新加载页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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