ChatGPT Preserve Prompt Textarea

To preserve last typed prompt messages for chat being switched

目前为 2023-07-16 提交的版本。查看 最新版本

// ==UserScript==
// @name        ChatGPT Preserve Prompt Textarea
// @namespace   UserScript
// @match       https://chat.openai.com/*
// @grant       none
// @version     0.1.0
// @author      CY Fung
// @license     MIT
// @run-at      document-idle
// @description To preserve last typed prompt messages for chat being switched
// ==/UserScript==


let isValid = () => { return false; }
const map = new Map();
(async () => {
  let wPathname = null;
  while (true) {
    await new Promise(r => requestAnimationFrame(r));
    let sPathname = location.pathname;
    if (wPathname === sPathname) continue;
    wPathname = sPathname;
    isValid = () => { return false }
    let expired = Date.now() + 200;
    while (Date.now() < expired) {
      let textarea = document.querySelector('textarea#prompt-textarea');
      if (textarea && !textarea.value) break;
      if (location.pathname !== sPathname) break;
      await new Promise(r => requestAnimationFrame(r));
    }
    if (location.pathname !== sPathname) continue;
    expired = Date.now() + 80;
    let s = map.get(location.pathname);
    if (s) {
      while (Date.now() < expired) {
        let textarea = document.querySelector('textarea#prompt-textarea');
        if (!textarea) break;
        if (location.pathname !== sPathname) break;
        if (textarea.value !== s) textarea.value = s;
        await new Promise(r => requestAnimationFrame(r));
      }
      let textarea = document.querySelector('textarea#prompt-textarea');
      if (textarea) {
        textarea.focus();
        textarea.value = '';
        try {
          document.execCommand("insertText", false, s)
        } catch (e) {
          textarea.value = s;
        }
      }
    }
    await new Promise(r => requestAnimationFrame(r));
    if (location.pathname !== sPathname) continue;
    ((pathname) => {
      isValid = function () { return location.pathname === pathname }
    })(location.pathname);
  }
})();

const eventHandler = (evt) => {
  if (((evt || 0).target || 0).id !== 'prompt-textarea') return;
  if (isValid()) {
    map.set(location.pathname, evt.target.value);
  }
}

document.addEventListener('keyup', eventHandler, true);
document.addEventListener('change', eventHandler, true);

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址