自动刷新GitHub页面

在 GitHub 任意非编辑页面首次访问时强制刷新一次,解决某些脚本和扩展不生效的问题

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// ==UserScript==
// @name         自动刷新GitHub页面
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  在 GitHub 任意非编辑页面首次访问时强制刷新一次,解决某些脚本和扩展不生效的问题
// @author       klcb2010
// @match        https://github.com/*
// @grant        none
// ==/UserScript==

(function () {
    'use strict';

    const REFRESH_FLAG = 'gh_auto_full_refresh_done';

    
    const excludeKeywords = ['edit', 'new', 'settings', 'upload', 'releases/new', 'issues/new', 'pull/new'];

    function isExcluded(url = location.href) {
        return excludeKeywords.some(keyword => url.includes(keyword));
    }

    function shouldRefresh() {
        return !sessionStorage.getItem(REFRESH_FLAG) && !isExcluded();
    }

    function forceFullReload() {
        sessionStorage.setItem(REFRESH_FLAG, 'true');
        console.log('[GitHub Auto Refresh] Forcing full reload:', location.href);
        setTimeout(() => {
            try {
                location.reload(true); 
            } catch (e) {
                console.warn('reload(true) failed, fallback to normal reload');
                location.reload();
            }
        }, 1000);
    }

    function resetFlagIfNavigated() {
        sessionStorage.removeItem(REFRESH_FLAG);
        console.log('[GitHub Auto Refresh] URL changed, reset flag');
    }

    function onUrlChange(callback) {
        let lastUrl = location.href;
        new MutationObserver(() => {
            if (location.href !== lastUrl) {
                lastUrl = location.href;
                callback();
            }
        }).observe(document.body, { childList: true, subtree: true });
    }

   
    if (shouldRefresh()) {
        forceFullReload();
    }

   
    onUrlChange(() => {
        resetFlagIfNavigated();
        if (shouldRefresh()) {
            forceFullReload();
        }
    });
})();