Greasy Fork

Greasy Fork is available in English.

OpenAI Chat Copy Code Button

Add a 'Copy Code' button to the bottom right hand of code blocks on chat.openai.com

当前为 2023-04-07 提交的版本,查看 最新版本

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

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

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

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

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

您需要先安装一款用户脚本管理器扩展后才能安装此脚本。

(我已经安装了用户脚本管理器,让我安装!)

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展,比如 Stylus,才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

您需要先安装一款用户样式管理器扩展后才能安装此样式。

(我已经安装了用户样式管理器,让我安装!)

// ==UserScript==
// @name         OpenAI Chat Copy Code Button
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Add a 'Copy Code' button to the bottom right hand of code blocks on chat.openai.com
// @author       Your Name
// @match        https://chat.openai.com/*
// @grant        none
// @license MIT
// ==/UserScript==

(function () {
    'use strict';

    const copyToClipboard = (text) => {
        navigator.clipboard.writeText(text).then(() => {
            console.log('Copied code to clipboard');
        }, (err) => {
            console.error('Failed to copy code: ', err);
        });
    };

    const addButton = (elem) => {
        const button = document.createElement('button');
        button.innerHTML = '📋 Copy Code';
        button.style.position = 'absolute';
        button.style.bottom = '8px';
        button.style.right = '8px';
        button.style.fontSize = '12px';
        button.style.padding = '4px 8px';
        button.style.border = '1px solid #ccc';
        button.style.borderRadius = '3px';
        button.style.background = 'rgba(0,0,0,0.1)';
        button.style.color = 'white';
        button.style.cursor = 'pointer';
        button.style.zIndex = '10';
        button.addEventListener('click', (e) => {
            e.stopPropagation();
            copyToClipboard(elem.querySelector('code').textContent);
        });

        elem.style.position = 'relative';
        elem.appendChild(button);
    };

    const observeCodeBlocks = () => {
        const codeBlocks = document.querySelectorAll('pre:not(.copy-code-processed)');
        if (codeBlocks.length) {
            codeBlocks.forEach(block => {
                addButton(block);
                block.classList.add('copy-code-processed');
            });
        }
    };

    const observer = new MutationObserver(observeCodeBlocks);
    observer.observe(document.body, { childList: true, subtree: true });

    observeCodeBlocks();
})();