JSON paste on textarea

Paste JSON on textarea

Verze ze dne 12. 06. 2021. Zobrazit nejnovější verzi.

K instalaci tototo skriptu si budete muset nainstalovat rozšíření jako Tampermonkey, Greasemonkey nebo Violentmonkey.

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

K instalaci tohoto skriptu si budete muset nainstalovat rozšíření jako Tampermonkey nebo Violentmonkey.

K instalaci tohoto skriptu si budete muset nainstalovat rozšíření jako Tampermonkey nebo Userscripts.

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

K instalaci tohoto skriptu si budete muset nainstalovat manažer uživatelských skriptů.

(Už mám manažer uživatelských skriptů, nechte mě ho nainstalovat!)

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install an extension such as Stylus to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

You will need to install a user style manager extension to install this style.

(Už mám manažer uživatelských stylů, nechte mě ho nainstalovat!)

// ==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...
})();