onVisibilityChange

Waits until the tab is focused, executing a callback function when it happens.

This script should not be not be installed directly. It is a library for other scripts to include with the meta directive // @require https://update.greatest.deepsurf.us/scripts/480374/1283358/onVisibilityChange.js

  1. // ==UserScript==
  2. // @name onVisibilityChange
  3. // @namespace http://tampermonkey.net/
  4. // @version 0.1
  5. // @description Waits until the tab is focused, executing a callback function when it happens.
  6. // @author IgnaV
  7. // @grant none
  8. // ==/UserScript==
  9.  
  10. const onVisibilityChange = (onFocus, onBlur, minTime = 0) => {
  11. let lastExecutionTime = 0;
  12.  
  13. document.addEventListener('visibilitychange', function() {
  14. const currentTime = Date.now();
  15.  
  16. if (currentTime - lastExecutionTime >= minTime * 1000) {}
  17. if (document.visibilityState === 'visible') {
  18. onFocus?.();
  19. } else {
  20. onBlur?.();
  21. }
  22.  
  23. lastExecutionTime = currentTime;
  24. });
  25. };