Smart Page Auto Refresh

Smoothly refreshes web pages when pressing Ctrl+R

目前為 2024-11-05 提交的版本,檢視 最新版本

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 Tampermonkey,才能安裝此腳本

您需要先安裝使用者腳本管理器擴充功能後才能安裝該腳本。

(我已經安裝了使用者腳本管理器,讓我安裝!)

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展,比如 Stylus,才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

你需要先安裝一款使用者樣式管理器擴展後才能安裝此樣式

(我已經安裝了使用者樣式管理器,讓我安裝!)

// ==UserScript==
// @name         Smart Page Auto Refresh
// @namespace    http://tampermonkey.net/
// @version      1.5
// @description  Smoothly refreshes web pages when pressing Ctrl+R
// @author       kequn yang
// @match        *://*
// @match        file:///*
// @match        http://127.0.0.1:*/*
// @match        http://localhost:*/*
// @grant        GM_addStyle
// @run-at       document-end
// @license MIT
// ==/UserScript==

(function() {
    'use strict';
    const REFRESH_INTERVAL = 1000;
    const STORAGE_KEY = 'autoRefreshEnabled';
    let isRefreshing = false;
    let refreshTimer = null;
    let lastContent = '';

    // 打印使用说明
    console.log(`%cSmart Page Auto Refresh Instructions`, 'font-size: 16px; font-weight: bold; color: #2196F3');
    console.log(`%cAutomatically refresh web pages. Press Ctrl+R to start/stop page refresh.`, 'color: #4CAF50');
    console.log(`\n%cFor CORS problem of local file, start Chrome with these parameters:`, 'color: #FF5722');
    console.log(`%c# MacOS`, 'color: #9C27B0');
    console.log(`open -a "Google Chrome" --args --allow-file-access-from-files --disable-web-security --user-data-dir="~/ChromeDevSession"`);
    console.log(`\n%c# Windows`, 'color: #9C27B0');
    console.log(`chrome.exe --allow-file-access-from-files --disable-web-security --user-data-dir=C:\\ChromeDevSession`);
    console.log(`\n%c# Linux`, 'color: #9C27B0');
    console.log(`google-chrome --allow-file-access-from-files --disable-web-security --user-data-dir="~/ChromeDevSession"`);

    function isLocalFile() {
        return window.location.protocol === 'file:';
    }

    async function checkForChanges() {
        if (!isRefreshing) return;

        try {
            const response = await fetch(window.location.href, {
                cache: 'no-store'  // 禁用缓存,确保获取最新内容
            });

            if (!response.ok) throw new Error('Network response was not ok');
            const newContent = await response.text();

            // 仅在内容真正改变时才刷新
            if (newContent !== lastContent) {
                console.log('Content changed, refreshing...');
                lastContent = newContent;
                window.location.reload();  // 直接刷新页面
            }
        } catch (error) {
            console.error('Refresh error:', error);
            stopAutoRefresh();  // 发生错误时停止刷新
        }
    }

    function startAutoRefresh() {
        if (isRefreshing) return;

        // 存储初始内容
        fetch(window.location.href, {
            cache: 'no-store'
        }).then(response => response.text())
          .then(content => {
              lastContent = content;
              isRefreshing = true;
              localStorage.setItem(STORAGE_KEY, 'true');

              if (refreshTimer) {
                  clearInterval(refreshTimer);
              }

              refreshTimer = setInterval(checkForChanges, REFRESH_INTERVAL);
              console.log('Auto refresh started');
          })
          .catch(error => {
              console.error('Error starting auto refresh:', error);
          });
    }

    function stopAutoRefresh() {
        if (!isRefreshing) return;

        isRefreshing = false;
        localStorage.setItem(STORAGE_KEY, 'false');

        if (refreshTimer) {
            clearInterval(refreshTimer);
            refreshTimer = null;
        }

        console.log('Auto refresh stopped');
    }

    function handleKeyPress(e) {
        if (e.ctrlKey && (e.key === 'r' || e.key === 'R')) {
            e.preventDefault();
            if (isRefreshing) {
                stopAutoRefresh();
            } else {
                startAutoRefresh();
            }
        }
    }

    // 初始化
    function initialize() {
        document.addEventListener('keydown', handleKeyPress);

        // 获取保存的状态
        const savedState = localStorage.getItem(STORAGE_KEY);
        if (savedState === 'true') {
            startAutoRefresh();
        }
    }

    // 运行初始化
    initialize();

    // 在页面卸载前清理
    window.addEventListener('unload', () => {
        if (refreshTimer) {
            clearInterval(refreshTimer);
        }
    });
})();