Alternate solution for the deprecated execCommand when copying a rich-text from the displayed HTML

41 Views Asked by At

I have this javascript to copy some rich text (for example bolds, tables, etc.) when a button is clicked:

<script>
    window.addEventListener( 'load', () => {
        const btnCopy = document.getElementById( 'my-nice-btn-copy' );
        const richTextToCopy = document.getElementById( 'some-complex-html-structure' );

        btnCopy.addEventListener('click', () => {
            const range = document.createRange();
            range.selectNode( richTextToCopy );
            window.getSelection().removeAllRanges();
            window.getSelection().addRange( range );

            document.execCommand( 'copy' );
            window.getSelection().removeAllRanges();
        });
    } );
</script>

PhpStorm tells me that execCommand() is deprecated.

Here it says I should use the Clipboard API but here it says I need to create a new ClipboardItem element and there I start getting lost.

How should I modify my javascript function to use the native Clipboard API?

0

There are 0 best solutions below