最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript execCommand("paste") not working - Stack Overflow

programmeradmin5浏览0评论

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 mand 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?

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 mand 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?

Share Improve this question asked Aug 28, 2016 at 17:17 The SimonThe Simon 1052 gold badges2 silver badges9 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 8

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 mand to paste

 document.execCommand('insertText' 

but you need to focus the textarea first

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

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

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 mand 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).

I had a same issue. hence as work around I used below code, its working with some limitation. give a try :)

navigator.clipboard.readText().then(function(text){ 
    document.execCommand( "insertHTML", false, text || "");
});
发布评论

评论列表(0)

  1. 暂无评论