javascript paste command

Asked

Viewed 791 times

3

How do I paste what’s in the clipboard?

I did a lot of research, but what I found was just the copy, not the necklace!

the only thing I found about necklace, it didn’t work, which was the document.execCommand("paste");

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

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

to test, I put the alert that in addition to not paste, displays: False

inserir a descrição da imagem aqui

I used this Question

  • Which location you want to copy from?

2 answers

6

Basically, you cannot access the clipboard content in most browsers. Because obviously this is considered a security problem, since any Javascript code could have access to things that may not not concern it.

However, it is possible to capture this content in the paste. Since, at this moment, the user 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>

  • So it’s not possible to paste? Too bad! I’ll have to come up with another strategy then. Thanks @Jbueno

  • @Fabiosouza needs to improve something in the answer?

  • thanks for the help, but my intention was to have a button paste, which would paste the contents of the clipboard. But soon I will use this code, I already have an idea for what I will do, and then I accept your answer OK.

0

Currently the best way to interact with the user’s transfer area is through the browser’s Clipboard API, through asynchronous methods such as this demonstrated in the documentation of the Mozilla.

Thus it becomes transparent to the user that his transfer area may be requested, because a dialog box will request his permission

navigator.clipboard.readText().then(text => alert(text));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.