Search code examples
javascriptonclicktextareaclipboardpaste

Pasting from clipboard into textarea using JavaScript onclick


I'm trying to implement the following scripts to allow me to paste from my clipboard into a textarea on my webpage in Chrome. They both demo perfectly on jsfiddle.net but I can't get it to work on my website. On jsfiddle, it prompted a warning to allow pasting from clipboard, as expected. On my site it did not. I also temporarily deleted any other files in the same folder invoking .js src scripts in case they were somehow interfering or overriding this code. (@Rob Louie - thank you for initialing posting these links a few years ago. I couldn't comment on that thread directly due to my newbie status.) Any help would be appreciated. Thank you.

https://jsfiddle.net/1vmansr2/

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {

   navigator.clipboard.readText()
.then(text => {
document.getElementById("demo").innerHTML = text;

})
.catch(err => {
document.getElementById("demo").innerHTML = 'Failed to read clipboard contents: '+err;
});


}
</script>

https://jsfiddle.net/zm490d6a/

<style>
    textarea {
  width: 300px;
  height: 400px;
}
</style>
<script async src="//jsfiddle.net/zm490d6a/embed/"></script>
<textarea onclick="paste(this)"></textarea>
<script>
    async function paste(input) {
        const text = await navigator.clipboard.readText();
        input.value = text;
      }
</script>

Solution

  • All else going correctly, you've probably blocked clipboard access on your website. You can change this by clicking the 'i' in a circle at the left of your Chrome URL bar.

    enter image description here