paste command in javascript

1

How do I paste what's on the clipboard?

I researched a lot, but what I found was just copying it, not the necklace!

The only thing I found about paste, did not work, which was document.execCommand("paste");

I want when the user clicks on the textbox or button, whatever was on the clipboard was pasted, so I did this:

        $("#URL").click( function () {
            document.execCommand("paste");
            alert(document.execCommand("paste"));
        });

To test, I put the alert which, in addition to not pasting, displays: False

Iusedthis Question

    
asked by anonymous 27.01.2017 / 12:19

1 answer

5

Basically, you can not access the contents of the clipboard in most browsers . Because of course this is considered a security issue, since any JavaScript code could have access to things that may not relate to it.

However, you can capture this content in the paste event. Since, at this time, the user has decided to share this content.

function handlePaste (e) {
    var clipboardData, pastedData;

    e.stopPropagation();
    e.preventDefault();

    clipboardData = e.clipboardData || window.clipboardData;
    pastedData = clipboardData.getData('Text');

    //pastedData tem o conteúdo da área de transferência
    console.log(pastedData); 
}

document.getElementById('editableDiv').addEventListener('paste', handlePaste);
<div id='editableDiv' contenteditable='true'>Cole algo aqui</div>
    
27.01.2017 / 12:33