V2EX Image paster

Automatically uploads pasted images to Imgur on V2EX input boxes

このスクリプトの質問や評価の投稿はこちら通報はこちらへお寄せください。
// ==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);
    }
})();