Skip to content
Advertisement

How to Copy Text to clipboard upon echo with PHP & JS?

apologies if this sounds super stupid.

I’ve spent some time trying to do this, and the only way I’ve found is after clicking something like a button.

I have a form for generating license keys and I would like to copy license key to clipboard after generation, so I’d like to know if there’s some JavaScript code that I can echo to make this work, so far I’ve had no luck with the below code:

<?php
echo
'<script>
var e = "texttocopy";
            var tempItem = document.createElement('input');
            tempItem.setAttribute('type','text');
            tempItem.setAttribute('display','none');
            let content = e;
            if (e instanceof HTMLElement) {
                    content = e.innerHTML;
            }
            tempItem.setAttribute('value',content);
            document.body.appendChild(tempItem);
            tempItem.select();
            document.execCommand('Copy');
            tempItem.parentElement.removeChild(tempItem);
            alert("Successfully copied the key to your clipboard!");
}
            </script>';
?>

I appreciate any help, thank you.

Advertisement

Answer

You can use navigator.clipboard.writeText.

<script>
navigator.clipboard.writeText('texttocopy');
</script>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement