Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript execCommand("paste") not working

Tags:

javascript

document.execCommand("Paste") doesn't work! "Copy" and "cut" works fine.

var editor = document.getElementById("ta1");
editor.focus();
editor.select();
var successful = document.execCommand("Paste");  
var msg = successful ? 'successful' : 'unsuccessful';  
alert('Pasting text command was ' + msg);

This alerts "unsuccessful" on paste, but "successful" on copy and cut..

I use the "copy" another place on my webpage, and the whole thing works like a charm, but I need to get "paste" working as well..

I'm using Chrome (no extension, just a regular webpage). Any ideas?

like image 486
The Simon Avatar asked Aug 28 '16 17:08

The Simon


People also ask

What can I use instead of execCommand copy?

The Clipboard API can be used instead of execCommand in many cases, but execCommand is still sometimes useful.

How do you paste in Javascript?

Use navigator. clipboard to get access to the clipboard. Use writeText() to copy text into the clipboard. Use readText() to paste the text.

How to read data from clipboard using javascript?

read() The read() method of the Clipboard interface requests a copy of the clipboard's contents, delivering the data to the returned Promise when the promise is resolved. Unlike readText() , the read() method can return arbitrary data, such as images. This method can also return text.


2 Answers

For security reason, it is blocked in chrome. Even office 365 asks to their users to use shortcuts ctrl+c/ctrl+v instead of copy.

this function is only available for chrome extension now.

if the text you want to copy has to be paste on the same page then just store the text in a variable, you can then use the following command to paste

 document.execCommand('insertText' 

but you need to focus the textarea first

and to copy the selection https://developer.mozilla.org/fr/docs/Web/API/Window/getSelection

full example https://jsfiddle.net/bormat/9a8nuzse/2/

like image 124
bormat Avatar answered Oct 02 '22 23:10

bormat


This is clearly mentioned in Mozilla Documentation of Document.execCommand() that:

paste

Pastes the clipboard contents at the insertion point (replaces current selection). Clipboard capability must be enabled in the user.js preference file. See 1.

1 Before Firefox 41, clipboard capability needed to be enabled in the user.js preference file. See A brief guide to Mozilla preferences for more information. If the command wasn't supported or enabled, execCommand was raising an exception instead of returning false.In Firefox 41 and later, clipboard capability are enabled by default in any event handler that is able to pop-up a window (semi-trusted scripts).

like image 23
Irfan Anwar Avatar answered Oct 02 '22 23:10

Irfan Anwar