V2EX Image paster

Automatically uploads pasted images to Imgur on V2EX input boxes

当前为 2023-06-28 提交的版本,查看 最新版本

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

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

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

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

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

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

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

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

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

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

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

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

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

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

// ==UserScript==
// @name         V2EX Image paster
// @namespace    v2ex-image-paster
// @version      1.0
// @description  Automatically uploads pasted images to Imgur on V2EX input boxes
// @match        https://www.v2ex.com/*
// @match        https://*
// @grant        GM_xmlhttpRequest
// @license      MIT
// ==/UserScript==

(function() {
    'use strict';

    // 监听粘贴事件
    document.addEventListener('paste', function(event) {
        var items = (event.clipboardData || event.originalEvent.clipboardData).items;
        for (var i = 0; i < items.length; i++) {
            var item = items[i];
            if (item.type.indexOf('image') !== -1) {
                // 获取粘贴的图片文件
                var file = item.getAsFile();

                // 上传图片到 Imgur
                uploadToImgur(file);

            }
        }
    });

    // 上传图片到 Imgur
    function uploadToImgur(file) {
        console.log('upload...')
        var formData = new FormData();
        formData.append('image', file);

        GM_xmlhttpRequest({
            method: 'POST',
            url: 'https://api.imgur.com/3/image',
            headers: {
                Authorization: 'Client-ID 1c49486ec8e9565'
            },
            data: formData,
            onload: function(response) {
                console.log(response)
                var json = JSON.parse(response.responseText);
                console.log(json)
                if (json.success) {
                    pasteTextAtCursor(`\n${json.data.link}`)
                }
            }
        });
    };
    function pasteTextAtCursor(text) {
        var textarea = document.activeElement;
        var startPos = textarea.selectionStart;
        var endPos = textarea.selectionEnd;

        textarea.value = textarea.value.substring(0, startPos) + text + textarea.value.substring(endPos);
        textarea.setSelectionRange(startPos + text.length, startPos + text.length);
    }
})();