简体   繁体   中英

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

I created a little script to keep the PHP session active even if the user does not refresh the page.

Here is the Javascript I'm using via PHP to keep the session alive:

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

It works fine, but I've noticed that it will keep calling the refreshTheSession.php script even if the page is not in focus , which I don't want because it means someone can leave a tab open with that page and keep the session alive indefinitely even if they are on a different tab doing something else.

I only want the session to stay alive if the user is still actively on the page in question.

Is it possible to do that? If so, how can I modify my code above to do that?

You don't tell me what "did not work" exactly, but the second link I commented, the Page Visibility API, will definitely do what you're asking for, as can be seen in this working example:

 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); 

Update: Using document.setFocus() , it would look like this:

 // 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. 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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