JSON paste on textarea

Paste JSON on textarea

当前为 2021-06-12 提交的版本,查看 最新版本

您需要先安装一个扩展,例如 篡改猴Greasemonkey暴力猴,之后才能安装此脚本。

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

您需要先安装一个扩展,例如 篡改猴暴力猴,之后才能安装此脚本。

您需要先安装一个扩展,例如 篡改猴Userscripts ,之后才能安装此脚本。

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

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

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

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

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

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

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

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

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

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

// ==UserScript==
// @name         JSON paste on textarea
// @version      0.1
// @description  Paste JSON on textarea
// @match        https://*/*
// @grant        none
// @namespace https://greasyfork.org/users/371179
// ==/UserScript==
(function() {
    'use strict';

    /*

    -- Example --
    https://jsonformatter.curiousconcept.com/
    "{\"a\":1,\"b\":2,\"c\":3,\"d\":\"A\",\"e\":\"B\",\"f\":\"C\"}"

    */

    function getClipText(evt) {

        var text;
        var clp = (evt.originalEvent || evt).clipboardData;
        if (clp === undefined || clp === null) {
            text = window.clipboardData.getData("text") || null;
        } else {
            text = clp.getData('text/plain') || null;
        }
        return text;

    }

    function changeText(evt, callback) {


        var text, newText;
        var clp = (evt.originalEvent || evt).clipboardData;
        if (clp === undefined || clp === null) {
            text = window.clipboardData.getData("text") || "";
            if (text !== "") {
                newText = callback(text);

                if (typeof newText == 'string' && newText != text) {
                    evt.preventDefault();
                    if (window.getSelection) {
                        var newNode = document.createElement("span");
                        newNode.innerHTML = newText;
                        window.getSelection().getRangeAt(0).insertNode(newNode);
                    } else {
                        document.selection.createRange().pasteHTML(newText);
                    }
                }
            }
        } else {
            text = clp.getData('text/plain') || "";
            if (text !== "") {
                newText = callback(text);
                if (typeof newText == 'string' && newText != text) {
                    evt.preventDefault();
                    document.execCommand('insertText', false, newText);
                }
            }
        }


    }

    //  =========================================================================================
    // https://stackoverflow.com/questions/7464282/javascript-scroll-to-selection-after-using-textarea-setselectionrange-in-chrome

    function setSelectionRange(textarea, selectionStart, selectionEnd) {
        // First scroll selection region to view
        const fullText = textarea.value;
        textarea.value = fullText.substring(0, selectionEnd);
        // For some unknown reason, you must store the scollHeight to a variable
        // before setting the textarea value. Otherwise it won't work for long strings
        const scrollHeight = textarea.scrollHeight
        textarea.value = fullText;
        let scrollTop = scrollHeight;
        const textareaHeight = textarea.clientHeight;
        if (scrollTop > textareaHeight) {
            // scroll selection to center of textarea
            scrollTop -= textareaHeight / 2;
        } else {
            scrollTop = 0;
        }
        textarea.scrollTop = scrollTop;

        // Continue to set selection range
        textarea.setSelectionRange(selectionStart, selectionEnd);
    }
    //  =========================================================================================


    if (document.queryCommandSupported("insertText")) {

        var object = {

            callback: function(str) {

                var targetElm = this.targetElm;
                var clipText = this.clipText;

                var newClipText = typeof str == 'string' ? str : clipText;
                if (newClipText != "") {


                    var oldText = targetElm.value
                    document.execCommand("insertText", false, newClipText);

                    if ('selectionStart' in targetElm) {
                        var afterChange = () => {
                            var newText = targetElm.value;
                            if (oldText == newText) return window.requestAnimationFrame(afterChange);
                            setSelectionRange(targetElm, targetElm.selectionStart, targetElm.selectionEnd);
                        };

                        window.requestAnimationFrame(afterChange);

                    }
                }

            }
        };


        document.addEventListener('paste', function(evt) {

            var clipText = getClipText(evt)
            if (clipText === null || typeof clipText != 'string') return;


            var targetElm = evt.target;

            if (!targetElm) return;

            switch (targetElm.tagName) {
                case 'TEXTAREA':
                    break;
                default:
                    return;
            }

            var testP = clipText.replace(/[0-9a-zA-Z\u4E00-\u9FFF\/\%\-\+\_\.\;\$\#]+/g, '').trim();
            var testR = /^[\:\[\]\{\}\,\s\n\"\'\\\/]+$/
            if (!testP) {
                return;
            }
            if (!testR.test(testP)) return;


            object.targetElm = targetElm;
            object.clipText = clipText;

            var res = null;
           try {
               res = new Function('return (' + clipText + ');')(); //backbracket to avoid return newline -> undefined
           } catch (e) {}

            if(typeof res=='string'){
                console.log('userscript - there is a text convertion to your pasted content');
            evt.preventDefault();
                object.callback(res);
            }


        }, {
            passive: false
        });
    }

    // Your code here...
})();