ChatGPT Input Protector

Prevent input words loss on ChatGPT page loading

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Greasemonkey 油猴子Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Violentmonkey 暴力猴,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 Tampermonkey 篡改猴Userscripts ,才能安装此脚本。

您需要先安装一款用户脚本管理器扩展,例如 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);
    });

})();