OpenAI Token Counter with Draggable Button

Count tokens of selected text with a draggable button

目前为 2024-01-06 提交的版本。查看 最新版本

// ==UserScript==
// @name         OpenAI Token Counter with Draggable Button
// @namespace    http://tampermonkey.net/
// @version      1.0
// @description  Count tokens of selected text with a draggable button
// @author       ChatGPT 4
// @match        *://*/*
// @grant        none
// @require      https://unpkg.com/gpt-tokenizer/dist/cl100k_base.js
// ==/UserScript==

(function() {
    'use strict';

    // 创建无文本的绿色按钮
    const button = document.createElement('button');
    button.style.position = 'fixed';
    button.style.right = '0px';
    button.style.bottom = '50%'; // 初始位置在屏幕垂直中间
    button.style.zIndex = '1000';
    button.style.width = '25px'; // 小一点的正方形
    button.style.height = '25px';
    button.style.backgroundColor = '#4CAF50';
    button.style.border = 'none';
    button.style.cursor = 'pointer';
    button.style.borderRadius = '5px';
    document.body.appendChild(button);

    // 创建弹窗
    const popup = document.createElement('div');
    popup.style.display = 'none';
    popup.style.position = 'fixed';
    popup.style.right = '20px';
    popup.style.bottom = '60px';
    popup.style.backgroundColor = '#333';
    popup.style.color = '#fff';
    popup.style.padding = '10px';
    popup.style.borderRadius = '5px';
    popup.style.zIndex = '1001';
    document.body.appendChild(popup);

    // 显示计数结果
    function showTokenCount(tokens) {
        popup.textContent = `Token count: ${tokens.length}`;
        popup.style.display = 'block';
        setTimeout(() => { popup.style.display = 'none'; }, 3000); // 3秒后隐藏
    }

    // 计算 Token 数量
    function countTokens() {
        const text = window.getSelection().toString();
        if (text) {
            const tokens = GPTTokenizer_cl100k_base.encode(text);
            showTokenCount(tokens);
        }
    }

    // 实现按钮的垂直拖动
    let isDragging = false;
    button.onmousedown = function(event) {
        isDragging = true;
        let shiftY = event.clientY - button.getBoundingClientRect().top;

        document.onmousemove = function(event) {
            if (isDragging) {
                let newTop = event.clientY - shiftY;
                button.style.top = newTop + 'px';
            }
        };

        document.onmouseup = function() {
            document.onmousemove = null;
            document.onmouseup = null;
            isDragging = false;
        };
    };

    button.ondragstart = function() {
        return false;
    };

    // 为按钮添加事件监听器
    button.addEventListener('click', countTokens);
})();

QingJ © 2025

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