Modify Clipboard content after copy event: JavaScript, jQuery

前端 未结 4 927
感情败类
感情败类 2020-12-15 12:30

My requirement: When user copy some content from my web page, with text some HTML tags and carriage retun also gets copied. I need to modify the copied cont

4条回答
  •  一个人的身影
    2020-12-15 12:39

    To resolve this issue what I have done on copy event I have bind a function i.e. copyToClipboard which creates a textarea at run time, copy modified clipboard data to this text area and then execute a 'CUT' command (to avoid recursive call on copy event). And finally deleting textarea element in finally block.

    Code:

    $(document).bind('copy', function () {
                var text = window.getSelection().toString().replace(/[\n\r]+/g, '');
                copyToClipboard(text);
            });
    
            function copyToClipboard(text) {
                    var textarea = document.createElement("textarea");
                    textarea.textContent = text;
                    textarea.style.position = "fixed";
                    document.body.appendChild(textarea);
                    textarea.select();
                    try {
                        return document.execCommand("cut");
                    } catch (ex) {
                        console.warn("Copy to clipboard failed.", ex);
                        return false;
                    } finally {
                        document.body.removeChild(textarea);
                    }
            }
    

提交回复
热议问题