Auto Refresh ChatGPT session

Auto refresh chatGPT session

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// ==UserScript==
// @name         Auto Refresh ChatGPT session
// @namespace    http://github.com/zhaohongxuan
// @version      0.5
// @description  Auto refresh chatGPT session
// @author       hank zhao
// @match        https://chat.openai.com/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=openai.com
// @grant        GM_notification
// @license      AGPL-3.0-or-later
// ==/UserScript==

(function() {
    'use strict';
    function showNotification() {
      const notification = new Notification("chatGPT session auto refresh Failed",{
          "body":"Click to reload manully",
          "icon":"https://www.google.com/s2/favicons?sz=64&domain=openai.com"
      })

      notification.onclick = (event) => {
          event.preventDefault(); // prevent the browser from focusing the Notification's tab
          location.reload()
      };
   }

    function checkPermissionAndNotify() {
        if (!("Notification" in window)) {
            alert("chatGPT session auto refresh Failed");
        } else if (Notification.permission === "granted") {
            showNotification()
        } else if (Notification.permission !== "denied") {
            Notification.requestPermission().then((permission) => {
                if (permission === "granted") {
                     showNotification()
                }
            });
        }
    }

    const intervalId = setInterval(function() {
          var xhr = new XMLHttpRequest()
          xhr.open('GET', "https://chat.openai.com/api/auth/session")
          xhr.onload = function() {
              if (xhr.status === 200) {
                console.debug('refresh chatGPT session Success')
              } else {
                console.warn('refresh chatGPT session Failed: ', xhr.status)
                clearInterval(intervalId)
                checkPermissionAndNotify()
              }
          }
          xhr.onerror = function() {
             console.warn('refresh chatGPT session Error: ', xhr.status)
             clearInterval(intervalId)
             checkPermissionAndNotify()
          }
          xhr.send()
    }, 10000);
})();