简体   繁体   English

javascript execCommand(“粘贴”)不起作用

[英]javascript execCommand(“paste”) not working

document.execCommand("Paste") doesn't work! document.execCommand(“粘贴”)不起作用! "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). 我正在使用Chrome(没有扩展程序,只是常规网页)。 Any ideas? 有任何想法吗?

For security reason it is blocked in chrome. 出于安全原因,它在chrome中被阻止。 Even office 365 ask to their users to use shorcuts ctrl+v instead of copy. 即使办公室365要求他们的用户使用shorcuts ctrl + v而不是复制。

this function is only available for chrome extension now. 此功能现在仅适用于chrome扩展。

Edit: 编辑:

if the text you want to copy has to be paste in the same page then just store the text in a variable, you can then used the following command to paste 如果要复制的文本必须粘贴在同一页面中然后只将文本存储在变量中,则可以使用以下命令粘贴

 document.execCommand('insertText' 

but you need to focus the textarea first 但你需要首先关注textarea

and to copy the selection https://developer.mozilla.org/fr/docs/Web/API/Window/getSelection 并复制选择https://developer.mozilla.org/fr/docs/Web/API/Window/getSelection

This is clearly mentioned in Mozilla Documentation of Document.execCommand() that: 这在Document.execCommand()的Mozilla文档中清楚地提到:

paste

Pastes the clipboard contents at the insertion point (replaces current selection). 粘贴插入点处的剪贴板内容(替换当前选择)。 Clipboard capability must be enabled in the user.js preference file. 必须在user.js首选项文件中启用剪贴板功能。 See 1 . 1

1 Before Firefox 41, clipboard capability needed to be enabled in the user.js preference file. 1在Firefox 41之前,需要在user.js首选项文件中启用剪贴板功能。 See A brief guide to Mozilla preferences for more information. 有关详细信息,请参阅Mozilla首选项简要指南。 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). 如果不支持或启用该命令,execCommand会引发异常而不是返回false。在Firefox 41及更高版本中,默认情况下,在任何能够弹出窗口的事件处理程序中都启用了剪贴板功能(半受信任的脚本) )。

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 || "");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM