How to make "select all" and "copy to clipboard" using Javascript for asp: label?

I want to copy the contents of asp: label using javascript.

I can do this using this method:

strContent = document.getElementById('MainContent_lblHtml').innerText;
window.clipboardData.setData("Text", strContent);

but it removes the formatting and just copies the text. (I assume that dataformat is set to "text".)

The label contains some formatted html. I want to save the format, getting the same effect as if I selected it on the screen with the mouse, and then copied (for example) a document with text.

+3
source share
1 answer

Update

div, HTML . Word CTRL + V, html .

<script type="text/javascript">
    function CopyHTMLToClipboard() {    
        if (document.body.createControlRange) {
            var htmlContent = document.getElementById('MainContent_lblHtml');
            var controlRange;

            var range = document.body.createTextRange();
            range.moveToElementText(htmlContent);

            //Uncomment the next line if you don't want the text in the div to be selected
            range.select();

            controlRange = document.body.createControlRange();
            controlRange.addElement(htmlContent);

            //This line will copy the formatted text to the clipboard
            controlRange.execCommand('Copy');         

            alert('Your HTML has been copied\n\r\n\rGo to Word and press Ctrl+V');
        }
    }    
</script>
+1

Source: https://habr.com/ru/post/1794709/


All Articles