简体   繁体   English

用户从其他选项卡返回时重新加载页面

[英]Reload page when user returns from other tab

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. 为此,当用户从另一个选项卡切换到带有网站的选项卡时,我需要刷新页面。

Is there a way to do this with JavaScript / jQuery? 有没有办法用JavaScript / jQuery做到这一点? I know that location.reload(); 我知道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). 用于刷新页面,但我不知道如何在选项卡再次激活(并且只有一次)时告诉JavaScript执行此操作。

You can use this: 你可以用这个:

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];
}
})();

Usage: 用法:

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

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

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

You can readabout this here: 你可以在这里读到这个:

Detect if browser tab is active or user has switched away 检测浏览器选项卡是否处于活动状态或用户是否已切换

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

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