ChatGPT Input Protector

Prevent input words loss on ChatGPT page loading

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// ==UserScript==
// @name         ChatGPT Input Protector
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  Prevent input words loss on ChatGPT page loading
// @match        https://chat.openai.com/*
// @match        https://chatgpt.com/* 
// @license MIT 
// ==/UserScript==

(function () {
    'use strict';

    const STORAGE_KEY = "chatgpt_input_cache";

    function getInputBox() {
        return document.querySelector('[contenteditable="true"]');
    }

    // 保存输入
    function saveInput(text) {
        localStorage.setItem(STORAGE_KEY, text);
    }

    // 读取输入
    function loadInput() {
        return localStorage.getItem(STORAGE_KEY) || "";
    }

    // 恢复输入
    function restoreInput(el) {
        const saved = loadInput();
        if (saved && el.innerText.trim() === "") {
            el.innerText = saved;

            // 触发 input 事件(关键!让 React 知道内容变了)
            el.dispatchEvent(new Event('input', { bubbles: true }));
        }
    }

    function init() {
        let input = getInputBox();
        if (!input) return;

        // 初次恢复
        restoreInput(input);

        // 监听输入变化
        input.addEventListener("input", () => {
            saveInput(input.innerText);
        });

        // 监听 DOM 变化(防止 React 重建)
        const observer = new MutationObserver(() => {
            let newInput = getInputBox();
            if (newInput && newInput !== input) {
                input = newInput;
                restoreInput(input);

                input.addEventListener("input", () => {
                    saveInput(input.innerText);
                });
            }
        });

        observer.observe(document.body, {
            childList: true,
            subtree: true
        });
    }

    // 等页面加载
    window.addEventListener("load", () => {
        setTimeout(init, 500);
    });

})();