Javascript/Jquery copy-paste command (Ctrl + c)

Asked

Viewed 5,739 times

3

I simply want the Javascript command that copies and pastes, regardless of whether it works on all browsers.

There is a similar question here. But it requires it to work on all browsers. Cross-browser way of copying text to Clipboard (Clipboard)

This other question does not meet my expectations as I literally need the Ctrl c command and do not need to run cross browser. (for the system will be just for me)

NOTE: It needs to be Javascript, nothing other languages.

  • I don’t understand why the question about copying text pro Clipboard doesn’t apply to your case. (And which browser you use?)

  • I think there was no need to duplicate your other question, 3 people already voted to reopen, it was only a matter of time and argue.

  • You still haven’t answered me, you want to copy the text from <div> or the <div> formatted (with styles etc) to paste into Word for example?

  • The @mgibsonbr response works in my case. (No browser preferences) No need to copy formatting, only content.

1 answer

4


Note: this solution is specific pro Internet Explorer

You can do this through the function execCommand:

  1. Create a range (range) and choose which part of your document will be covered by that range:

    var range = document.createRange();
    range.selectNode(divACopiar);
    
  2. Place this interval in the window selection:

    window.getSelection().addRange(range);
    
  3. Invoke the command copy:

    var sucesso = document.execCommand("copy");
    

In doing so, the browser will display a security alert, asking the user to give permission to their page to access the clipboard:

inserir a descrição da imagem aqui

If the user allows, the function will return true and the content of div chosen will be in the clipboard.

Example in jsFiddle.

  • 1

    This worked on my Chrome/OSX (no security alert).

  • Very good, I used window.getSelection(). removeAllRanges(); to remove text selection and make it invisible to user.

Browser other questions tagged

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