V2EX Image paster

Automatically uploads pasted images to Imgur on V2EX input boxes

目前為 2023-06-28 提交的版本,檢視 最新版本

您需要先安裝使用者腳本管理器擴展,如 TampermonkeyGreasemonkeyViolentmonkey 之後才能安裝該腳本。

You will need to install an extension such as Tampermonkey to install this script.

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyViolentmonkey 後才能安裝該腳本。

您需要先安裝使用者腳本管理器擴充功能,如 TampermonkeyUserscripts 後才能安裝該腳本。

你需要先安裝一款使用者腳本管理器擴展,比如 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);
    }
})();