Greasy Fork is available in English.

Простое удаление разговоров Claude

Добавляет кнопку в правом нижнем углу веб-страницы Claude для легкого удаления разговоров. Выберите флажки рядом с разговорами, которые вы хотите удалить, затем нажмите кнопку «Удалить разговоры». Перед окончательным удалением разговоров вам будет предложено подтвердить действие.

// ==UserScript==
// @name      Easy Delete Claude Conversations
// @name:zh-TW   簡單刪除 Claude 對話
// @name:zh-CN   简单删除 Claude 对话
// @name:ja      Claudeの会話を簡単に削除
// @name:ko      Claude 대화 쉽게 삭제하기
// @name:ru      Простое удаление разговоров Claude
// @name:fr      Suppression facile des conversations Claude
// @name:en      Easy Delete Claude Conversations
// @version      0.3
// @description  Adds a button to the bottom right corner of the Claude webpage to easily delete conversations. Select the checkboxes next to the conversations you want to delete, then click the "Delete Conversations" button. You'll be prompted to confirm before the conversations are permanently deleted.
// @description:zh-TW  在 Claude 網頁的右下角添加一個按鈕,可以輕鬆刪除對話。選中要刪除的對話旁邊的複選框,然後點擊"刪除對話"按鈕。在對話被永久刪除之前,將會彈出二次確認提示。
// @description:zh-CN  在 Claude 网页的右下角添加一个按钮,可以轻松删除对话。选中要删除的对话旁边的复选框,然后点击"删除对话"按钮。在对话被永久删除之前,将会弹出二次确认提示。
// @description:ja     Claudeのウェブページの右下隅にボタンを追加し、会話を簡単に削除できるようにします。削除したい会話の横にあるチェックボックスを選択し、「会話を削除」ボタンをクリックします。会話が完全に削除される前に、確認を求められます。
// @description:ko     Claude 웹페이지의 오른쪽 하단 모서리에 버튼을 추가하여 대화를 쉽게 삭제할 수 있습니다. 삭제할 대화 옆의 체크박스를 선택한 다음 "대화 삭제" 버튼을 클릭합니다. 대화가 영구적으로 삭제되기 전에 확인을 요청받게 됩니다.
// @description:ru     Добавляет кнопку в правом нижнем углу веб-страницы Claude для легкого удаления разговоров. Выберите флажки рядом с разговорами, которые вы хотите удалить, затем нажмите кнопку «Удалить разговоры». Перед окончательным удалением разговоров вам будет предложено подтвердить действие.
// @description:fr     Ajoute un bouton dans le coin inférieur droit de la page Web Claude pour supprimer facilement les conversations. Cochez les cases à côté des conversations que vous souhaitez supprimer, puis cliquez sur le bouton "Supprimer les conversations". Vous serez invité à confirmer avant que les conversations ne soient définitivement supprimées.
// @description:en     Adds a button to the bottom right corner of the Claude webpage to easily delete conversations. Select the checkboxes next to the conversations you want to delete, then click the "Delete Conversations" button. You'll be prompted to confirm before the conversations are permanently deleted.
// @author       zetaduncan
// @match        https://claude.ai/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=claude.ai
// @grant        unsafeWindow
// @license      MIT
// @namespace https://github.com/username/ClaudeConversationDeleter
// ==/UserScript==

(() => {
    const getCookieValue = (name) => (
        document.cookie.split('; ').find(row => row.startsWith(`${name}=`))?.split('=')[1] ?? undefined
    );

    const org = getCookieValue('lastActiveOrg');
    if (!org) {
        console.error("Cannot get current organization ID");
        return;
    }

    let checkboxesVisible = false;
    let chats = [];

    // Function to fetch chat conversations and add checkboxes
    const fetchAndAddCheckboxes = async () => {
        try {
            const response = await fetch(`https://claude.ai/api/organizations/${org}/chat_conversations`, {
                method: "GET",
                credentials: "include",
            });
            chats = await response.json();

            // Find the chat containers and add checkboxes
            chats.forEach(chat => {
                const chatElement = document.querySelector(`a[href="/chat/${chat.uuid}"]`);
                if (chatElement && !chatElement.parentNode.nextElementSibling?.querySelector('input[type="checkbox"]')) {
                    const checkboxContainer = document.createElement('div');
                    checkboxContainer.style.marginTop = '5px';
                    const checkbox = document.createElement('input');
                    checkbox.type = 'checkbox';
                    checkbox.dataset.chatId = chat.uuid;
                    checkboxContainer.appendChild(checkbox);
                    chatElement.parentNode.parentNode.insertBefore(checkboxContainer, chatElement.parentNode.nextSibling);
                }
            });

            // Add "Select All" checkbox at the top
            if (!document.getElementById('selectAllCheckbox')) {
                const selectAllContainer = document.createElement('div');
                selectAllContainer.style.marginBottom = '10px';
                const selectAllCheckbox = document.createElement('input');
                selectAllCheckbox.type = 'checkbox';
                selectAllCheckbox.style.marginRight = '5px';
                selectAllCheckbox.id = 'selectAllCheckbox';
                selectAllCheckbox.addEventListener('change', () => {
                    const checkboxes = document.querySelectorAll('input[type="checkbox"]');
                    checkboxes.forEach(checkbox => {
                        if (checkbox.id !== 'selectAllCheckbox') {
                            checkbox.checked = selectAllCheckbox.checked;
                        }
                    });
                });

                const selectAllLabel = document.createElement('label');
                selectAllLabel.textContent = {
                    'en': 'Select All',
                    'zh-TW': '全選',
                    'zh-CN': '全选',
                    'ja': 'すべて選択',
                    'ko': '모두 선택',
                    'ru': 'Выбрать все',
                    'fr': 'Tout sélectionner'
                }[navigator.language] || 'Select All';
                selectAllContainer.appendChild(selectAllCheckbox);
                selectAllContainer.appendChild(selectAllLabel);

                const previousChatsHeader = document.querySelector('h3.text-sm.text-center.text-text-400');
                if (previousChatsHeader) {
                    previousChatsHeader.parentNode.insertBefore(selectAllContainer, previousChatsHeader);
                }
            }

            checkboxesVisible = true;
        } catch (error) {
            console.error("Failed to fetch chat conversations:", error);
        }
    };

    // Function to handle deleting specific chat logs
    const deleteChats = async (chatIds) => {
        try {
            await Promise.all(
                chatIds.map(id => fetch(`https://claude.ai/api/organizations/${org}/chat_conversations/${id}`, {
                    method: "DELETE",
                    credentials: "include",
                }))
            );
            window.location.reload(); // Refresh to update the list
        } catch (error) {
            console.error("Error clearing history:", error);
        }
    };

    // Clear history modified to handle selective deletion
    unsafeWindow.clearHistory = async () => {
        if (!checkboxesVisible) {
            await fetchAndAddCheckboxes();
        } else {
            const selectedChats = Array.from(document.querySelectorAll('input[type="checkbox"]:checked'))
                .filter(checkbox => checkbox.id !== 'selectAllCheckbox')
                .map(checkbox => checkbox.dataset.chatId);

            if (selectedChats.length > 0) {
                const confirmMessage = {
                    'en': `Are you sure you want to delete the selected ${selectedChats.length} conversation(s)?`,
                    'zh-TW': `確定要刪除選定的 ${selectedChats.length} 個對話嗎?`,
                    'zh-CN': `确定要删除选定的 ${selectedChats.length} 个对话吗?`,
                    'ja': `選択した${selectedChats.length}件の会話を削除してもよろしいですか?`,
                    'ko': `선택한 ${selectedChats.length}개의 대화를 삭제하시겠습니까?`,
                    'ru': `Вы уверены, что хотите удалить выбранные разговоры (${selectedChats.length})?`,
                    'fr': `Êtes-vous sûr de vouloir supprimer les ${selectedChats.length} conversation(s) sélectionnée(s) ?`
                }[navigator.language] || `Are you sure you want to delete the selected ${selectedChats.length} conversation(s)?`;

                if (confirm(confirmMessage)) {
                    deleteChats(selectedChats);
                }
            } else if (selectedChats.length === 0) {
                const checkboxes = document.querySelectorAll('input[type="checkbox"]');
                checkboxes.forEach(checkbox => {
                    if (checkbox.id !== 'selectAllCheckbox') {
                        checkbox.parentNode.remove();
                    }
                });
                const selectAllCheckbox = document.getElementById('selectAllCheckbox');
                if (selectAllCheckbox) {
                    selectAllCheckbox.parentNode.remove();
                }
                checkboxesVisible = false;
            }
        }
    };

    // Function to create the button and set up event listeners
    const createButton = () => {
        const button = document.createElement("button");
        button.textContent = {
            'en': 'Delete Conversations',
            'zh-TW': '刪除對話',
            'zh-CN': '删除对话',
            'ja': '会話を削除',
            'ko': '대화 삭제',
            'ru': 'Удалить разговоры',
            'fr': 'Supprimer les conversations'
        }[navigator.language] || 'Delete Conversations';
        button.style.position = 'fixed';
        button.style.right = '20px';
        button.style.bottom = '20px';
        button.style.zIndex = 1000;
        button.classList.add("block", "p-4");
        button.addEventListener("click", () => {
            unsafeWindow.clearHistory();
        });
        document.body.appendChild(button);
    };

    createButton();
})();