I am running a script which prevents a particular website from logging out by refreshing the page every few minutes. The issues I have is that the refresh occurs even if I am actively using the page.
I would like the following script to run only if the current tab running the page is inactive.
Do I need to use some type of event handler or can I simply call on the page visibility API and run if state = ‘any other state than visible’?
Very new to javscript 🙂
// ==UserScript==
// @name Tony TIMS Refresh
// @namespace TonyPony
// @description Reload pages every 1 minutes
// @version 0.2
// @match
// @match https://THE PAGE I WANT TO REFRESH
// @match
// @grant none
// ==/UserScript==
(function() {
'use strict';
setTimeout(function(){ location.reload(); }, 60*1000);
})();
I am not sure how I would implement either of my suggestions.
2
Answers
you can use the Page Visibility API. This API allows you to determine if a tab is currently active or not, and based on that, you can choose to run your script or not.
note: that not all browsers support the Page Visibility API, so you may want to implement a fallback method using the
onblur
event handler as well.You can achieve the desired behavior of refreshing a page only when the tab is inactive using the Page Visibility API in JavaScript. This API allows you to determine whether the current tab is visible or hidden to the user.
Here is a simple example script that demonstrates this functionality:
This script will refresh the page at a defined interval only when the tab is inactive. You can adjust the reloadInterval variable to set the desired time interval for refreshing the page. Run this script in an HTML file and check the console to see the page refresh when the tab is inactive.
I hope this helps! Let me know if you have any further questions.