ChatGPT Előzmények Törlése 🕶️

Automatikusan törli a csevegés előzményeit a chatgpt.com látogatásakor

Szkript telepítése?
A szerző által javasolt szkript

Ez is érdekelhet: DuckDuckGPT 🤖

Szkript telepítése
// ==UserScript==
// @name                Autoclear ChatGPT History
// @name:af             Verwyder ChatGPT Geskiedenis 🕶️
// @name:am             በተሻለ ChatGPT ጉዳዮ ማግኘት 🕶️
// @name:ar             مسح تاريخ ChatGPT 🕶️
// @name:az             ChatGPT Tarixini Təmizləyin 🕶️
// @name:be             Ачысціць гісторыю ChatGPT 🕶️
// @name:bem            Lekeni ChatGPT History 🕶️
// @name:bg             Изчистете ChatGPT История 🕶️
// @name:bn             চ্যাটজিপিটি ইতিহাস মুছে ফেলুন 🕶️
// @name:bo             ChatGPT སྐད་དོན་ཚར་བཟོ། 🕶️
// @name:bs             Obriši ChatGPT historiju 🕶️
// @name:ca             Esborra l'historial de ChatGPT 🕶️
// @name:ceb            Autoclear ChatGPT Kasaysayan 🕶️
// @name:ckb            بسڕەوەی مێژووی ChatGPT 🕶️
// @name:cs             Vymazat ChatGPT Historii 🕶️
// @name:cy             Clirio Hanes ChatGPT 🕶️
// @name:da             Ryd ChatGPT Historik 🕶️
// @name:de             ChatGPT-Verlauf löschen 🕶️
// @name:dv             ChatGPT ހިސްތުކުރުން ފުހެވޭނީ 🕶️
// @name:dz             ChatGPT སྐད་ཆ་འབད་བཅུ་ 🕶️
// @name:el             Διαγραφή Ιστορικού ChatGPT 🕶️
// @name:eo             Forviŝi ChatGPT Historion 🕶️
// @name:es             Borrar Historial de ChatGPT 🕶️
// @name:et             Kustuta ChatGPT Ajalugu 🕶️
// @name:eu             Ezabatu ChatGPT Historia 🕶️
// @name:fa             پاک کردن تاریخچه ChatGPT 🕶️
// @name:fi             Poista ChatGPT:n historia 🕶️
// @name:fo             Strika ChatGPT Søgu 🕶️
// @name:fr             Effacer l'historique de ChatGPT 🕶️
// @name:fr-CA          Effacer l'historique de ChatGPT 🕶️
// @name:gd             Lùghdaich Eachdraidh ChatGPT 🕶️
// @name:gl             Limpar Historial de ChatGPT 🕶️
// @name:gu             આપો ChatGPT ઇતિહાસ 🕶️
// @name:haw            Kāpaki Kākoʻo i ka Moʻolelo o ChatGPT 🕶️
// @name:he             מחק את היסטוריית ChatGPT 🕶️
// @name:hi             ChatGPT इतिहास को हटाएं 🕶️
// @name:hr             Izbriši ChatGPT Povijest 🕶️
// @name:ht             Efase ChatGPT Istwa 🕶️
// @name:hu             ChatGPT Előzmények Törlése 🕶️
// @name:hy             Ջնջել ChatGPT-ի Պատմությունը 🕶️
// @name:id             Hapus Riwayat ChatGPT 🕶️
// @name:is             Eyða ChatGPT Saga 🕶️
// @name:it             Cancella Cronologia ChatGPT 🕶️
// @name:ja             ChatGPT の履歴を削除する 🕶️
// @name:jv             Hapus Riwayat ChatGPT 🕶️
// @name:ka             ChatGPT-ის ისტორიის გასუფთავება 🕶️
// @name:kab            Sken ChatGPT Tamɣarit 🕶️
// @name:kk             ChatGPT Тарихын Жою 🕶️
// @name:km             លុបប្រវត្តិសាស្រ្ត ChatGPT 🕶️
// @name:kn             ChatGPT ಇತಿಹಾಸವನ್ನು ಅಳಿಸಿ 🕶️
// @name:ko             ChatGPT 기록 지우기 🕶️
// @name:ku             Çavkaniya ChatGPTê Paqij bike 🕶️
// @name:ky             ChatGPT Тарыхын Жок Кыл 🕶️
// @name:la             Eximitte Historiam ChatGPT 🕶️
// @name:lb             Läschen ChatGPT Geschicht 🕶️
// @name:lo             ລຶບບັນດາຕິນມັກສະບັບ ChatGPT 🕶️
// @name:lt             Išvalyti ChatGPT Istoriją 🕶️
// @name:lv             Notīrīt ChatGPT Vēsturi 🕶️
// @name:mg             Mamafa ny ChatGPT Historique 🕶️
// @name:mi             Muku ChatGPT Hītori 🕶️
// @name:mk             Избриши го Историјата на ChatGPT 🕶️
// @name:ml             ചാറ്റ്‌ജിപിടി ചരിത്രം മായ്ക്കുക 🕶️
// @name:mn             ChatGPT Түүхийг устгах 🕶️
// @name:ms             Padam Sejarah ChatGPT 🕶️
// @name:mt             Ħassar It-Twaħħil ChatGPT 🕶️
// @name:my             ဆက်လက် ChatGPT သမိုင်းကို ဖျက်ပစ်နေပါသည် 🕶️
// @name:ne             Autoclear ChatGPT इतिहास 🕶️
// @name:nl             Wis ChatGPT Geschiedenis 🕶️
// @name:no             Autoclear ChatGPT Historie 🕶️
// @name:ny             Tikalonso ChatGPT Chisulo 🕶️
// @name:pa             ਚੈਟਜੀਪੀਟੀ ਇਤਿਹਾਸ ਮਿਟਾਓ 🕶️
// @name:pap            Bula Historia di ChatGPT 🕶️
// @name:pl             Wyczyść Historię ChatGPT 🕶️
// @name:ps             د ChatGPT د تاریخ پاکول 🕶️
// @name:pt             Limpar Histórico do ChatGPT 🕶️
// @name:pt-BR          Limpar Histórico do ChatGPT 🕶️
// @name:rn             Kwihesha ChatGPT Byinshi 🕶️
// @name:ro             Ștergeți Istoricul ChatGPT 🕶️
// @name:ru             Очистить Историю ChatGPT 🕶️
// @name:rw             Fata ChatGPT Itangazo 🕶️
// @name:sg             Mbama ChatGPT Makumbe 🕶️
// @name:si             නැවත සංවේදී ChatGPT ඉතිරිකිරීම 🕶️
// @name:sk             Vymažte ChatGPT Históriu 🕶️
// @name:sl             Počisti Zgodovino ChatGPT 🕶️
// @name:sm             Masi ChatGPT Faʻaipoipoga 🕶️
// @name:sn             Tirisa ChatGPT Chiremba 🕶️
// @name:so             Ka Saar Tareenka ChatGPT 🕶️
// @name:sr             Обриши историју ChatGPT-а 🕶️
// @name:sv             Rensa ChatGPT Historik 🕶️
// @name:sw             Futa Historia ya ChatGPT 🕶️
// @name:ta             தானாகவே அழிக்க சேட்ஜிபிடி வரலாற்றை 🕶️
// @name:te             ChatGPT చరిత్రను తొలగించు 🕶️
// @name:tg             Тозаиши корҳои ChatGPT 🕶️
// @name:th             ล้างประวัติศาสตร์ ChatGPT 🕶️
// @name:ti             ምርግጋጽ ChatGPT ኣጸዓይ ፈጥር 🕶️
// @name:tk             ChatGPT Tarixini Aýyr 🕶️
// @name:tn             Futa ChatGPT Tlhahlobo 🕶️
// @name:to             Fakatonu ChatGPT History 🕶️
// @name:tpi            Kolim ChatGPT Stori 🕶️
// @name:tr             ChatGPT Geçmişi Temizle 🕶️
// @name:uk             Очистити Історію ChatGPT 🕶️
// @name:ur             ChatGPT کی تاریخ صاف کریں 🕶️
// @name:uz             ChatGPT Tarixini Tozalash 🕶️
// @name:vi             Xóa Lịch Sử ChatGPT 🕶️
// @name:xh             Qhipha ChatGPT Isaziso 🕶️
// @name:yi             ויסמעקן טשאַטגפּט געשיכטע 🕶️
// @name:zh             自动清除 ChatGPT 历史记录 🕶️
// @name:zh-CN          自动清除 ChatGPT 历史记录 🕶️
// @name:zh-HK          自動清除 ChatGPT 歷史記錄 🕶️
// @name:zh-SG          自动清除 ChatGPT 历史记录 🕶️
// @name:zh-TW          自動清除 ChatGPT 歷史記錄 🕶️
// @name:zu             Sula ChatGPT Isifundo 🕶️
// @description         Auto-clears chat history when visiting chatgpt.com
// @description:af      Skoonmaak Chat Geskiedenis wanneer jy chatgpt.com besoek
// @description:am      የ chatgpt.com ጸሃይ ታክሲን በማግኘት ታከለው
// @description:ar      يقوم تلقائيًا بمسح سجل المحادثات عند زيارة chatgpt.com
// @description:az      chatgpt.com-a gedəndə avtomatik olaraq söhbət tarixini təmizləyir
// @description:be      Аўтаматычна ачышчае гісторыю чата пры наведванні chatgpt.com
// @description:bem     Chibwezache Mphindi Zochitika Pamene Kumatemba chatgpt.com
// @description:bg      Автоматично изчиства чат историята при посещение на chatgpt.com
// @description:bn      যখন chatgpt.com পরিদর্শন করা হলে অটোমেটিকভাবে চ্যাট ইতিহাস মুছে ফেলে
// @description:bo      དཔེར་ན་ chatgpt.com འགྲེལ་བཤད་འདི་ལུ་ སྤྱོད་ཡོད་མི་འདི་བལྟ་མི་བཟོ།
// @description:bs      Automatski briše istoriju chata prilikom posjete chatgpt.com
// @description:ca      S'elimina automàticament l'historial de xats en visitar chatgpt.com
// @description:ceb     Automatic gidut-ana sa kasaysayan sa chat sa pagbisita sa chatgpt.com
// @description:ckb     دهستکاریکردنی مێژووی گفتوگۆکان خۆکارانه بۆ سەردانی chatgpt.com
// @description:cs      Automaticky vymaže historii chatu při návštěvě chatgpt.com
// @description:cy      Mae'n glirio hanes sgwrs yn awtomatig wrth ymweld â chatgpt.com
// @description:da      Renser automatisk chatloggen ved besøg på chatgpt.com
// @description:de      Löscht den Chatverlauf automatisch beim Besuch von chatgpt.com
// @description:dv      chatgpt.com އެކައުންމަދުގެ ޗެކުމު ހުރިހައްދަވާނެ ޗައިންކުރޭ
// @description:dz      འཛུགས་མིག་འདི་ལུ་ chatgpt.com འགྲེལ་བཤད་རོགས་བསྐྱེད་ཡོད།
// @description:el      Αυτόματη διαγραφή ιστορικού συνομιλίας κατά την επίσκεψη στο chatgpt.com
// @description:eo      Memorigo de la babilado aŭtomate malaperas dum vizito ĉe chatgpt.com
// @description:es      Borra automáticamente el historial de chat al visitar chatgpt.com
// @description:et      Kustutab automaatselt vestluse ajaloo, kui külastate saiti chatgpt.com
// @description:eu      Berezgaitasunez ezabatzen du txataren historia chatgpt.com bisitatzen denean
// @description:fa      پاک کردن خودکار تاریخچه چت در هنگام بازدید از chatgpt.com
// @description:fi      Poistaa keskusteluhistorian automaattisesti käydessä chatgpt.comissa
// @description:fo      Auto-rensar spjall søguna tá tú vitjar chatgpt.com
// @description:fr      Efface automatiquement l'historique des discussions lors de la visite de chatgpt.com
// @description:fr-CA   Efface automatiquement l'historique des discussions lors de la visite de chatgpt.com
// @description:gd      Thoir aire bheagachaidh air eachdraidh na còmhraidh nuair a tha thu a' tadhal air chatgpt.com
// @description:gl      Limpa automáticamente o historial do chat ao visitar chatgpt.com
// @description:gu      chatgpt.com મુકે છે નાતીજે જ્ઞાનવર્ધક ચેટ નો ઇતિહાસ
// @description:haw     Mālama haku ʻinoʻino pāhana hoʻohānau mai ana i chatgpt.com
// @description:he      מנקה באופן אוטומטי את היסטוריית הצ'אט בעת ביקור ב-chatgpt.com
// @description:hi      chatgpt.com पर आवर्तित होने पर चैट इतिहास को स्वचालित रूप से साफ करता है
// @description:hr      Automatski briše povijest razgovora prilikom posjeta chatgpt.com
// @description:ht      Auto-efase istwa chat la lè vizite chatgpt.com
// @description:hu      Automatikusan törli a csevegés előzményeit a chatgpt.com látogatásakor
// @description:hy      Պատմությունը ինքնաշխատանքային մաքրում է chatgpt.com այցելելուն դեպի
// @description:id      Menghapus otomatis riwayat obrolan saat mengunjungi chatgpt.com
// @description:is      Hreinsar sjálfvirkt spjallshönnun þegar heimsókn er gerð á chatgpt.com
// @description:it      Cancella automaticamente la cronologia della chat durante la visita a chatgpt.com
// @description:ja      chatgpt.com を訪れる際に自動的にチャット履歴を消去します
// @description:jv      Otomatis ngapus riwayat obrolan nalika ngunjungi chatgpt.com
// @description:ka      თავისითად წაშლის ჩათის ისტორიას chatgpt.com-ზე მომსახურების დროს
// @description:kab     Ireɣsan Ayren Tisstrir ChatGPT I yur-s achatgpt.com
// @description:kk      chatgpt.com-ды көруге бастап автоматты түрде чат тарихын жою
// @description:km      លុបសេវាកម្មប្រវត្តិការណ៍ជជែកពីព័ត៌មានមនុស្សកន្លងទៅកាន់ chatgpt.com
// @description:kn      chatgpt.com ಸಂದರ್ಶಿಸಿದಾಗ ಸ್ವಯಂಚಾಲಿತವಾಗಿ ಚಾಟ್ ಇತಿಹಾಸವನ್ನು ಅಳಿಸುತ್ತದೆ
// @description:ko      chatgpt.com 방문 시 채팅 기록을 자동으로 지웁니다
// @description:ku      Çêkirina historyaya chatê di hembêzkirina chatgpt.com de
// @description:ky      chatgpt.com барысында түр кат жазмаларын автоматтык түрде жок этиш
// @description:la      Automate chat historia clearum cum chatgpt.com adibvisam
// @description:lb      Läscht automatesch d'Chat-Geschicht wéini een chatgpt.com besicht
// @description:lo      ລຶບປະວັດການສົນທະນາໃນຖ້າເຂົ້າຊົມ chatgpt.com
// @description:lt      Automatiškai išvalo pokalbių istoriją apsilankius chatgpt.com
// @description:lv      Automātiski notīra čata vēsturi, apmeklējot chatgpt.com
// @description:mg      Mamafa tsy ampy lalao ny tetikasa vaovao rehefa mitovy amin'ny chatgpt.com
// @description:mi      Auto-kōmata e whakakore i te hītori whakawhiti kōrero i te toro ki te chatgpt.com
// @description:mk      Автоматски брише историја на разговорот при посета на chatgpt.com
// @description:ml      chatgpt.com സന്ദർശിക്കുമ്പോൾ ചാറ്റ് ചരിത്രം ഓട്ടോ-പിന്തുണച്ച് അഴിച്ചുവയ്ക്കുന്നു
// @description:mn      chatgpt.com-оос орж ирэх үед чатын түүхийг автоматаар цэвэрлэнэ
// @description:ms      Membersihkan sejarah perbualan secara automatik apabila melawat chatgpt.com
// @description:mt      Jħassar awtomatikament il-kronoloġija tal-chat meta żżur chatgpt.com
// @description:my      chatgpt.com ကိုသွားဖို့အတွက် စကားဝှက်မှတ်တမ်းကို အလိုလိုရွေးချယ်ရန် အလွယ်တကူပြန်ဖွင့်ထားသည်
// @description:ne      chatgpt.com मा आएकोमा च्याट इतिहास स्वचालित रूपमा हटाउँछ
// @description:nl      Wis automatisch de chatgeschiedenis bij een bezoek aan chatgpt.com
// @description:no      Sletter automatisk samtalehistorikk ved besøk på chatgpt.com
// @description:ny      Kwatsa makina m'chipatala cha chat pamene kuwona chatgpt.com
// @description:pa      chatgpt.com ਦੇ ਦੌਰਾਨ ਚੈਟ ਇਤਿਹਾਸ ਆਟੋਮੈਟਿਕ ਕਲੀਅਰ ਹੋ ਜਾਂਦਾ ਹੈ
// @description:pap     Limpieza automático di historial di chat na bishita chatgpt.com
// @description:pl      Automatycznie czyści historię czatu podczas odwiedzania chatgpt.com
// @description:ps      خودکار تاریخچه چت پاک کول په chatgpt.com کښې
// @description:pt      Limpa automaticamente o histórico de bate-papo ao visitar chatgpt.com
// @description:pt-BR   Limpa automaticamente o histórico de bate-papo ao visitar chatgpt.com
// @description:rn      Guteza inkuru y'ikarita y'imibare igihe utanga chatgpt.com
// @description:ro      Șterge automat istoricul chat-ului la vizitarea chatgpt.com
// @description:ru      Автоматически очищает историю чата при посещении chatgpt.com
// @description:rw      Inyunganira amakuru ya chat inyuma yuko umaze guhamagara chatgpt.com
// @description:sg      Auto-kura kolibatalu ya misamba wakari karika kutɔbɔ chatgpt.com
// @description:si      chatgpt.com වෙත පැය සඳහා ස්වයංක්‍රීයතාවයින් චැට් ඉතිරිකිරීම මකා දැමුම
// @description:sk      Automaticky vymazáva históriu chatu pri návšteve chatgpt.com
// @description:sl      Samodejno izbriše zgodovino klepeta ob obisku spletnega mesta chatgpt.com
// @description:sm      Automa i le malologa o le sootaga i luma i le chatgpt.com
// @description:sn      Inongorora chat history chinayo ipapo uchi chiri kunochinja chatgpt.com
// @description:so      Wax ka qaad chatka markii la booqdo chatgpt.com
// @description:sr      Аутоматски брише историју чата при посети chatgpt.com
// @description:sv      Rensar automatiskt chattens historik vid besök på chatgpt.com
// @description:sw      Inaondoa historia ya mazungumzo moja kwa moja wakati wa kutembelea chatgpt.com
// @description:ta      chatgpt.com அடுத்தடுத்தப்படும் நேரத்தில் உரையாடல் வரலாறை தானியங்கே நீக்குகிறது
// @description:te      chatgpt.com సందర్శించినప్పుడు స్వయంచాలకంగా చాట్ చరిత్రను తొలగిస్తుంది
// @description:tg      Тарихи чатро худкор ҷоба кунед, ки chatgpt.com равед
// @description:th      ล้างประวัติการสนทนาโดยอัตโนมัติเมื่อเข้าชม chatgpt.com
// @description:ti      ኮምፕዩተር እየጠበቀ ጊዜ chatgpt.com የተሰኘውን ችግርን አስፈልጋል
// @description:tk      chatgpt.com-a ugradykda çat görnüşini awtomatiki biçimde boşaltýar
// @description:tn      Emucisha chat chinyakanyaka nga uwonawo chatgpt.com
// @description:to      'Oku fa'a kovi 'e he ngaahi sipoti fakamatala 'i he falelotu ki he chatgpt.com
// @description:tpi     Autometik klia chat histeri long bisitim long chatgpt.com
// @description:tr      chatgpt.com'u ziyaret ettiğinizde sohbet geçmişini otomatik olarak temizler
// @description:uk      Автоматично очищає історію чату при відвідуванні chatgpt.com
// @description:ur      chatgpt.com کے دورے پر چیٹ تاریخ خودکار طور پر صاف کرتا ہے
// @description:uz      chatgpt.com saytini tashrif buyurganda chat tarixini avtomatik ravishda o'chiradi
// @description:vi      Xóa lịch sử trò chuyện tự động khi ghé thăm chatgpt.com
// @description:xh      Ingqalasela ihisitela le-chat uma uzithola chatgpt.com
// @description:yi      רומט די פֿונען דער שאַט היסטאָריע ביי בעזוך בקוקן chatgpt.com
// @description:zh      访问 chatgpt.com 时自动清除聊天记录
// @description:zh-CN   访问 chatgpt.com 时自动清除聊天记录
// @description:zh-HK   訪問 chatgpt.com 時自動清除聊天記錄
// @description:zh-SG   访问 chatgpt.com 时自动清除聊天记录
// @description:zh-TW   訪問 chatgpt.com 時自動清除聊天記錄
// @description:zu      Ziba itshala lokucabanga okuzoshintshwa ngokuzenzakalelayo uma ukubuka chatgpt.com
// @author              Adam Lui
// @namespace           https://github.com/adamlui
// @version             2024.5.17.6
// @license             MIT
// @icon                https://media.autoclearchatgpt.com/images/icons/openai/black/icon48.png?a8868ef
// @icon64              https://media.autoclearchatgpt.com/images/icons/openai/black/icon64.png?a8868ef
// @compatible          chrome
// @compatible          edge
// @compatible          firefox
// @compatible          opera
// @compatible          brave
// @compatible          vivaldi
// @compatible          librewolf
// @compatible          ghost
// @compatible          qq
// @match               *://chatgpt.com/*
// @match               *://chat.openai.com/*
// @run-at              document-end
// @require             https://cdn.jsdelivr.net/npm/@kudoai/chatgpt.js@2.9.2/dist/chatgpt.min.js#sha256-5K/Bxm9bvGpV6dIHShz4o0fwPmIbIJxZAcddpzGFhck=
// @connect             cdn.jsdelivr.net
// @connect             greasyfork.org
// @grant               GM_setValue
// @grant               GM_getValue
// @grant               GM_registerMenuCommand
// @grant               GM_unregisterMenuCommand
// @grant               GM_openInTab
// @grant               GM.xmlHttpRequest
// @noframes
// @homepageURL         https://www.autoclearchatgpt.com
// @supportURL          https://support.autoclearchatgpt.com
// ==/UserScript==

// Documentation: https://docs.autoclearchatgpt.com
// NOTE: This script relies on the powerful chatgpt.js library @ https://chatgpt.js.org © 2023–2024 KudoAI & contributors under the MIT license.

(async () => {

    // Init CONFIG
    const config = {
        appName: 'Autoclear ChatGPT History', appSymbol: '🕶️',
        keyPrefix: 'autoclearChatGPThistory', userLanguage: chatgpt.getUserLanguage(),
        gitHubURL: 'https://github.com/adamlui/autoclear-chatgpt-history',
        greasyForkURL: 'https://greasyfork.org/scripts/460805-autoclear-chatgpt-history' }
    config.updateURL = config.greasyForkURL.replace('https://', 'https://update.')
        .replace(/(\d+)-?([a-zA-Z-]*)$/, (_, id, name) => `${ id }/${ !name ? 'script' : name }.meta.js`)
    config.supportURL = 'https://support.autoclearchatgpt.com'
    config.assetHostURL = config.gitHubURL.replace('github.com', 'cdn.jsdelivr.net/gh') + '@16d188e/'
    loadSetting('autoclear', 'buttonHidden', 'notifDisabled', 'toggleHidden')

    // Define MESSAGES
    let msgs = {};
    const msgsLoaded = new Promise(resolve => {
        const msgHostDir = config.assetHostURL + 'greasemonkey/_locales/',
              msgLocaleDir = ( config.userLanguage ? config.userLanguage.replace('-', '_') : 'en' ) + '/'
        let msgHref = msgHostDir + msgLocaleDir + 'messages.json', msgXHRtries = 0
        GM.xmlHttpRequest({ method: 'GET', url: msgHref, onload: onLoad })
        function onLoad(resp) {
            try { // to return localized messages.json
                const msgs = JSON.parse(resp.responseText), flatMsgs = {}
                for (const key in msgs)  // remove need to ref nested keys
                    if (typeof msgs[key] == 'object' && 'message' in msgs[key])
                        flatMsgs[key] = msgs[key].message
                resolve(flatMsgs)
            } catch (err) { // if bad response
                msgXHRtries++ ; if (msgXHRtries == 3) return resolve({}) // try up to 3X (original/region-stripped/EN) only
                msgHref = config.userLanguage.includes('-') && msgXHRtries == 1 ? // if regional lang on 1st try...
                    msgHref.replace(/([^_]*)_[^/]*(\/.*)/, '$1$2') // ...strip region before retrying
                        : ( msgHostDir + 'en/messages.json' ) // else use default English messages
                GM.xmlHttpRequest({ method: 'GET', url: msgHref, onload: onLoad })
            }
        }
    }) ; if (!/^en/.test(config.userLanguage)) try { msgs = await msgsLoaded; } catch (err) {}

    // Init/register MENU
    const state = {
        symbol: ['✔️', '❌'], word: ['ON', 'OFF'],
        separator: getUserscriptManager() == 'Tampermonkey' ? ' — ' : ': ' }
    let menuIDs = [] ; registerMenu() // create browser toolbar menu

    // Init UI flags
    await chatgpt.isLoaded()
    const isFirefox = chatgpt.browser.isFirefox(),
          isGPT4oUI = !!document.documentElement.className.includes(' ')

    // Add/update TWEAKS style
    const tweaksStyleUpdated = 202405171 // datestamp of last edit for this file's `tweaksStyle`
    let tweaksStyle = document.getElementById('tweaks-style') // try to select existing style
    if (!tweaksStyle || parseInt(tweaksStyle.getAttribute('last-updated'), 10) < tweaksStyleUpdated) { // if missing or outdated
        if (!tweaksStyle) { // outright missing, create/id/attr/append it first
            tweaksStyle = document.createElement('style') ; tweaksStyle.id = 'tweaks-style'
            tweaksStyle.setAttribute('last-updated', tweaksStyleUpdated.toString())
            document.head.append(tweaksStyle)
        }
        tweaksStyle.innerText = (
            '.chatgpt-modal button {'
              + 'font-size: 0.77rem ; text-transform: uppercase ;'
              + 'border-radius: 0 !important ; padding: 5px !important ; min-width: 102px }'
          + '.modal-buttons { margin-left: -13px !important }'
          + '* { scrollbar-width: thin }' // make FF scrollbar skinny to not crop toggle
          + '.sticky div:active, .sticky div:focus {' // post-GPT-4o UI sidebar
              + 'transform: none !important }' // disable distracting click zoom effect
        )
    }

    // Create nav TOGGLE div, add styles
    const navToggleDiv = document.createElement('div')
    navToggleDiv.style.maxHeight = '44px' // prevent flex overgrowth
    navToggleDiv.style.margin = '2px 0' // add v-margins
    navToggleDiv.style.userSelect = 'none' // prevent highlighting
    navToggleDiv.style.cursor = 'pointer' // add finger cursor
    updateToggleHTML() // create children

    // Insert sidebar toggle
    await chatgpt.sidebar.isLoaded() ; insertToggle()

    // Borrow/assign classes from sidebar div
    const firstLink = document.querySelector('nav a[href="/"]')
    const firstIcon = firstLink?.querySelector('div:first-child'),
          firstLabel = firstLink?.querySelector('div:nth-child(2)')
    navToggleDiv.classList.add(...firstLink.classList, ...firstLabel.classList)
    navToggleDiv.querySelector('img')?.classList.add(...firstIcon.classList)

    // Add LISTENER to toggle switch/label/config/menu + auto-clear
    navToggleDiv.addEventListener('click', () => {
        const toggleInput = document.querySelector('#acToggleInput')
        toggleInput.checked = !toggleInput.checked
        config.autoclear = toggleInput.checked
        updateToggleHTML()
        for (const id of menuIDs) { GM_unregisterMenuCommand(id) } registerMenu() // refresh menu
        if (config.autoclear) {
            setTimeout(chatgpt.clearChats, 250)
            if (!config.notifDisabled) notify(( msgs.mode_autoClear || 'Auto-Clear' ) + ': ON')
        } else if (!config.autoclear)
            if (!config.notifDisabled) notify(( msgs.mode_autoClear || 'Auto-Clear' ) + ': OFF')
        saveSetting('autoclear', config.autoclear)
    })

    // Monitor node changes to update sidebar toggle visibility
    const nodeObserver = new MutationObserver(mutations => {
        mutations.forEach(mutation => {
            if (mutation.type == 'childList' && mutation.addedNodes.length) {
                insertToggle()
    }})}) ; nodeObserver.observe(document.documentElement, { childList: true, subtree: true })

    // AUTO-CLEAR on first visit if enabled
    if (config.autoclear) {
        setTimeout(() => chatgpt.clearChats(), 250)
        if (!config.notifDisabled) notify(( msgs.mode_autoClear || 'Auto-Clear' ) + ': ON')
    }

    // Define SCRIPT functions

    function loadSetting(...keys) { keys.forEach(key => { config[key] = GM_getValue(config.keyPrefix + '_' + key, false) })}
    function saveSetting(key, value) { GM_setValue(config.keyPrefix + '_' + key, value) ; config[key] = value }
    function safeWindowOpen(url) { window.open(url, '_blank', 'noopener') } // to prevent backdoor vulnerabilities
    function getUserscriptManager() { try { return GM_info.scriptHandler } catch (err) { return 'other' }}

    // Define MENU functions

    function registerMenu() {
        menuIDs = [] // empty to store newly registered cmds for removal while preserving order

        // Add command to toggle auto-clear
        const acLabel = state.symbol[+!config.autoclear] + ' '
                      + ( msgs.menuLabel_autoClear || 'Autoclear Chats' )
                      + state.separator + state.word[+!config.autoclear]
        menuIDs.push(GM_registerMenuCommand(acLabel, () => {
            document.querySelector('#acToggleLabel').click()
        }))

        // Add 'Toggle Visibility' command
        const tvLabel = state.symbol[+config.toggleHidden] + ' '
                      + ( msgs.menuLabel_toggleVis || 'Toggle Visibility' )
                      + state.separator + state.word[+config.toggleHidden]
        menuIDs.push(GM_registerMenuCommand(tvLabel, () => {
            saveSetting('toggleHidden', !config.toggleHidden)
            navToggleDiv.style.display = config.toggleHidden ? 'none' : 'flex' // toggle visibility
            if (!config.notifDisabled) {
                notify(( msgs.menuLabel_toggleVis || 'Toggle Visibility' ) + ': '+ state.word[+config.toggleHidden])
            } for (const id of menuIDs) { GM_unregisterMenuCommand(id) } registerMenu() // refresh menu
        }))

        // Add command to show notifications when changing settings/modes
        const mnLabel = state.symbol[+config.notifDisabled] + ' '
                      + ( msgs.menuLabel_modeNotifs || 'Mode Notifications' )
                      + state.separator + state.word[+config.notifDisabled]
        menuIDs.push(GM_registerMenuCommand(mnLabel, () => {
            saveSetting('notifDisabled', !config.notifDisabled)
            notify(( msgs.menuLabel_modeNotifs || 'Mode Notifications' ) + ': ' + state.word[+config.notifDisabled])
            for (const id of menuIDs) { GM_unregisterMenuCommand(id) } registerMenu() // refresh menu
        }))

        // Add command to launch About modal
        const amLabel = '💡 ' + ( msgs.menuLabel_about || 'About' ) + ' '
                      + ( msgs.appName || config.appName )
        menuIDs.push(GM_registerMenuCommand(amLabel, launchAboutModal))
    }

    function launchAboutModal() {

        // Init data/styles
        const chatgptJSver = (/chatgpt-([\d.]+)\.min/.exec(GM_info.script.header) || [null, ''])[1],
              headingStyle = 'font-size: 1.15rem',
              pStyle = 'position: relative ; left: 3px',
              pBrStyle = 'position: relative ; left: 4px ',
              aStyle = 'color: ' + ( chatgpt.isDarkMode() ? '#c67afb' : '#8325c4' ) // purple

        // Show alert
        const aboutAlertID = alert(
            msgs.appName || config.appName, // title
            `<span style="${ headingStyle }"><b>🏷️ <i>${ msgs.about_version || 'Version' }</i></b>: </span>`
                + `<span style="${ pStyle }">${ GM_info.script.version }</span>\n`
            + `<span style="${ headingStyle }"><b>⚡ <i>${ msgs.about_poweredBy || 'Powered by' }</i></b>: </span>`
                + `<span style="${ pStyle }"><a style="${ aStyle }" href="https://chatgpt.js.org" target="_blank" rel="noopener">`
                + 'chatgpt.js</a>' + ( chatgptJSver ? ( ' v' + chatgptJSver ) : '' ) + '</span>\n'
            + `<span style="${ headingStyle }"><b>📜 <i>${ msgs.about_sourceCode || 'Source code' }</i></b>:</span>\n`
                + `<span style="${ pBrStyle }"><a href="${ config.gitHubURL }" target="_blank" rel="nopener">`
                + config.gitHubURL + '</a></span>',
            [ // buttons
                function checkForUpdates() { updateCheck() },
                function getSupport() { safeWindowOpen(config.supportURL) },
                function leaveAReview() { // show review modal
                    const reviewAlertID = chatgpt.alert(( msgs.alert_choosePlatform || 'Choose a platform' ) + ':', '',
                        [ function greasyFork() { safeWindowOpen(config.greasyForkURL + '/feedback#post-discussion') },
                          function futurepedia() { safeWindowOpen(
                              'https://www.futurepedia.io/tool/autoclear-chatgpt-history#autoclear-chatgpt-history-review') }])
                    document.getElementById(reviewAlertID).querySelector('button')
                        .style.display = 'none' }, // hide dismiss button
                function moreChatGPTapps() { safeWindowOpen('https://github.com/adamlui/chatgpt-apps') }
            ], '', 478 // set width
        )

        // Re-format buttons to include emoji + localized label + hide Dismiss button
        for (const button of document.getElementById(aboutAlertID).querySelectorAll('button')) {
            if (/updates/i.test(button.textContent)) button.textContent = (
                '🚀 ' + ( msgs.buttonLabel_updateCheck || 'Check for Updates' ))
            else if (/support/i.test(button.textContent)) button.textContent = (
                '🧠 ' + ( msgs.buttonLabel_getSupport || 'Get Support' ))
            else if (/review/i.test(button.textContent)) button.textContent = (
                '⭐ ' + ( msgs.buttonLabel_leaveReview || 'Leave a Review' ))
            else if (/apps/i.test(button.textContent)) button.textContent = (
                '🤖 ' + ( msgs.buttonLabel_moreApps || 'More ChatGPT Apps' ))
            else button.style.display = 'none' // hide Dismiss button
        }
    }

    function updateCheck() {

        // Fetch latest meta
        const currentVer = GM_info.script.version
        GM.xmlHttpRequest({
            method: 'GET', url: config.updateURL + '?t=' + Date.now(),
            headers: { 'Cache-Control': 'no-cache' },
            onload: response => { const updateAlertWidth = 377

                // Compare versions
                const latestVer = /@version +(.*)/.exec(response.responseText)[1]
                for (let i = 0 ; i < 4 ; i++) { // loop thru subver's
                    const currentSubVer = parseInt(currentVer.split('.')[i], 10) || 0,
                          latestSubVer = parseInt(latestVer.split('.')[i], 10) || 0
                    if (currentSubVer > latestSubVer) break // out of comparison since not outdated
                    else if (latestSubVer > currentSubVer) { // if outdated

                        // Alert to update
                        const updateAlertID = alert(( msgs.alert_updateAvail || 'Update available' ) + '! 🚀', // title
                            ( msgs.alert_newerVer || 'An update to' ) + ' ' // msg
                                + ( msgs.appName || config.appName ) + ' '
                                + `(v ${ latestVer }) ${ msgs.alert_isAvail || 'is available' }!   `
                                + '<a target="_blank" rel="noopener" style="font-size: 0.7rem" '
                                    + 'href="' + config.gitHubURL + '/commits/main/greasemonkey/'
                                    + config.updateURL.replace(/.*\/(.*)meta\.js/, '$1user.js') + '" '
                                    + `> ${ msgs.link_viewChanges || 'View changes' }</a>`,
                            function update() { // button
                                GM_openInTab(config.updateURL.replace('meta.js', 'user.js') + '?t=' + Date.now(),
                                    { active: true, insert: true })}, // focus, make adjacent                            
                            '', updateAlertWidth
                        )

                        // Localize button labels if needed
                        if (!config.userLanguage.startsWith('en')) {
                            const updateAlert = document.querySelector(`[id="${ updateAlertID }"]`),
                                  updateBtns = updateAlert.querySelectorAll('button')
                            updateBtns[1].textContent = msgs.buttonLabel_update || 'Update'
                            updateBtns[0].textContent = msgs.buttonLabel_dismiss || 'Dismiss'
                        }

                        return
                }}

                // Alert to no update, return to About alert
                alert(( msgs.alert_upToDate || 'Up-to-date' ) + '!', // title
                    `${ msgs.appName || config.appName } (v${ currentVer }) ` // msg
                        + ( msgs.alert_isUpToDate || 'is up-to-date' ) + '!',
                    '', '', updateAlertWidth
                )
                launchAboutModal()
    }})}

    // Define FEEDBACK functions

    function notify(msg, position = '', notifDuration = '', shadow = '') {
        chatgpt.notify(`${ config.appSymbol } ${ msg }`, position, notifDuration, shadow || chatgpt.isDarkMode() ? '' : 'shadow') }

    function alert(title = '', msg = '', btns = '', checkbox = '', width = '') {
        return chatgpt.alert(`${ config.appSymbol } ${ title }`, msg, btns, checkbox, width )}

    // Define UI functions

    async function insertToggle() {
        await chatgpt.history.isLoaded()

        // Insert toggle
        const parentToInsertInto = document.querySelector('nav '
            + ( isGPT4oUI ? '.sticky div' // new chat div
                          : '> div:not(.invisible)' )) // upper nav div
        if (!parentToInsertInto.contains(navToggleDiv)) {
            if (isGPT4oUI) try { parentToInsertInto.append(navToggleDiv) } catch (err) {}
            else try { parentToInsertInto.insertBefore(navToggleDiv, parentToInsertInto.children[1]) } catch (err) {}
        }

        // Tweak styles
        parentToInsertInto.style.backgroundColor = ( // hide transparency revealing chat log
            chatgpt.isDarkMode() ? '#0d0d0d' : '#f9f9f9' )
        navToggleDiv.style.paddingLeft = '8px'
        document.querySelector('#acToggleFavicon').src = `${ // update navicon color in case scheme changed
            config.assetHostURL }media/images/icons/incognito/${
            chatgpt.isDarkMode() ? 'white' : 'black' }/icon32.png`
    }

    function updateToggleHTML() {

        // Create/size/position navicon
        const navicon = document.querySelector('#acToggleFavicon') || document.createElement('img')
        navicon.id = 'acToggleFavicon'
        navicon.style.width = navicon.style.height = '1.25rem'
        navicon.style.marginLeft = isGPT4oUI ? '2px' : '4px' ; navicon.style.marginRight = '4px'

        // Create/ID/disable/hide/update checkbox
        const toggleInput = document.querySelector('#acToggleInput') || document.createElement('input')
        toggleInput.id = 'acToggleInput' ; toggleInput.type = 'checkbox' ; toggleInput.disabled = true
        toggleInput.style.display = 'none' ; toggleInput.checked = config.autoclear

        // Create/ID/stylize switch
        const switchSpan = document.querySelector('#acSwitchSpan') || document.createElement('span')
        switchSpan.id = 'acSwitchSpan'
        const switchStyles = {
            position: 'relative', left: `${ chatgpt.browser.isMobile() ? 211 : isGPT4oUI ? 147 : 152 }px`,
            backgroundColor: toggleInput.checked ? '#ccc' : '#AD68FF', // init opposite  final color
            bottom: `${ isFirefox || !isGPT4oUI ? 0.05 : 0 }em`, width: '30px', height: '15px',
            '-webkit-transition': '.4s', transition: '0.4s',  borderRadius: '28px'
        }
        Object.assign(switchSpan.style, switchStyles)

        // Create/ID/stylize knob, append to switch
        const knobSpan = document.querySelector('#acToggleKnobSpan') || document.createElement('span')
        knobSpan.id = 'acToggleKnobSpan'
        const knobWidth = 13
        const knobStyles = {
            position: 'absolute', left: '3px', bottom: '0.055em',
            width: `${ knobWidth }px`, height: `${ knobWidth }px`, content: '""', borderRadius: '28px',
            transform: toggleInput.checked ? // init opposite final pos
                'translateX(0)' : `translateX(${ knobWidth }px) translateY(0)`,
            backgroundColor: 'white',  '-webkit-transition': '0.4s', transition: '0.4s'
        }
        Object.assign(knobSpan.style, knobStyles) ; switchSpan.append(knobSpan)

        // Create/ID/stylize/fill label
        const toggleLabel = document.querySelector('#acToggleLabel') || document.createElement('label')
        toggleLabel.id = 'acToggleLabel'
        toggleLabel.style.marginLeft = '-41px' // left-shift to navicon
        toggleLabel.style.cursor = 'pointer' // add finger cursor on hover
        toggleLabel.style.width = `${ chatgpt.browser.isMobile() ? 201 : isGPT4oUI ? 145 : 148 }px` // to truncate overflown text
        toggleLabel.style.overflow = 'hidden' // to truncate overflown text
        toggleLabel.style.textOverflow = 'ellipsis' // to truncate overflown text
        toggleLabel.innerText = ( msgs.mode_autoClear || 'Auto-clear' ) + ' '
                              + ( toggleInput.checked ? ( msgs.state_enabled  || 'enabled' )
                                                      : ( msgs.state_disabled || 'disabled' ))
        // Append elements
        for (const elem of [navicon, toggleInput, switchSpan, toggleLabel]) navToggleDiv.append(elem)

        // Update visual state
        navToggleDiv.style.display = config.toggleHidden ? 'none' : 'flex'
        setTimeout(() => {
            if (toggleInput.checked) {
                switchSpan.style.backgroundColor = '#AD68FF'
                switchSpan.style.boxShadow = '2px 1px 9px #D8A9FF'
                knobSpan.style.transform = `translateX(${ knobWidth }px) translateY(0)`
            } else {
                switchSpan.style.backgroundColor = '#CCC'
                switchSpan.style.boxShadow = 'none'
                knobSpan.style.transform = 'translateX(0)'
            }
        }, 1) // min delay to trigger transition fx
    }

})()