如何设置 AJAX 间隔以便仅在页面仍处于焦点时刷新?

How to set AJAX interval so that it only refreshes if the page is still in focus?

我创建了一个小脚本来保持 PHP 会话处于活动状态,即使用户不刷新页面也是如此。

这是 Javascript 我通过 PHP 使会话保持活动状态的方法:

echo 'setInterval(function(){$.post(\'/refreshTheSession.php\');},90000);';

它工作正常,但我注意到它会继续调用 refreshTheSession.php 脚本 即使页面未处于焦点状态 ,我没有想要,因为这意味着有人可以在该页面打开一个选项卡并无限期地保持会话活动,即使他们在不同的选项卡上做其他事情也是如此。

我只希望会话在用户仍在相关页面上时保持活动状态。

可以吗?如果是这样,我该如何修改上面的代码来做到这一点?

你没有告诉我 "did not work" 到底是什么,但我评论的第二个 link 页面可见性 API 肯定会满足你的要求,因为可以在这个工作示例中看到:

function isDocumentVisible() {
 return !(document.hidden || document.webkitHidden || document.msHidden);
}

// this is what you'd output via PHP:
setInterval(function(){
 if (isDocumentVisible()) {
   $.post('/refreshTheSession.php');}
  }
 , 90000);

// for the sake of demonstrating that this example is indeed working:
window.setInterval(function() {
console.log(isDocumentVisible() ? "document is visible, refresh session" : "document is not visible, don't refresh session");
}, 1000);

更新: 使用 document.setFocus(),它看起来像这样:

// this is what you'd output via PHP:
setInterval(function(){
 if (document.hasFocus()) {
   $.post('/refreshTheSession.php');}
  }
 , 90000);

// for the sake of demonstrating that this example is indeed working:
window.setInterval(function() {
console.log(document.hasFocus() ? "document has focus, refresh session" : "document does not have focus, don't refresh session");
}, 1000);
Click into and out of the result iframe to see the focus change.