Smart Page Auto Refresh

Intelligently refreshes web pages only when content changes - no configuration needed

目前为 2024-11-05 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Smart Page Auto Refresh
  3. // @namespace http://tampermonkey.net/
  4. // @version 1.0
  5. // @description Intelligently refreshes web pages only when content changes - no configuration needed
  6. // @author kequn yang
  7. // @match *://*
  8. // @match file:///*
  9. // @grant none
  10. // @run-at document-end
  11. // @license MIT
  12. // ==/UserScript==
  13.  
  14. (function() {
  15. 'use strict';
  16. let lastContentHash = '';
  17. const REFRESH_INTERVAL = 1000; // 1 second default interval
  18. function getContentHash() {
  19. const content = document.body.innerHTML;
  20. let hash = 0;
  21. for (let i = 0; i < content.length; i++) {
  22. const char = content.charCodeAt(i);
  23. hash = ((hash << 5) - hash) + char;
  24. hash = hash & hash;
  25. }
  26. return hash.toString();
  27. }
  28. function hasContentChanged() {
  29. const currentHash = getContentHash();
  30. const hasChanged = lastContentHash !== currentHash;
  31. lastContentHash = currentHash;
  32. return hasChanged;
  33. }
  34.  
  35. async function checkAndRefresh() {
  36. try {
  37. const response = await fetch(window.location.href);
  38. const text = await response.text();
  39. const tempDiv = document.createElement('div');
  40. tempDiv.innerHTML = text;
  41. if (hasContentChanged()) {
  42. window.location.reload();
  43. }
  44. } catch (error) {
  45. window.location.reload();
  46. }
  47. }
  48.  
  49. function setupAutoRefresh() {
  50. lastContentHash = getContentHash();
  51. setInterval(checkAndRefresh, REFRESH_INTERVAL);
  52. }
  53.  
  54. setupAutoRefresh();
  55. })();