2017-06-27 1 views
5

テキストを入力するために隠しテキスト領域を使用し、それを選択してからdocument.execCommandを使用してクリップボードにコピーします。これは通常動作しますが、テキストが大きい場合は失敗します(falseを返します)。 Chrome v55では、約180K文字が失敗するようです。大文字のテキストでdocument.execCommand( 'copy')を使用してクリップボードにコピーするとエラーが発生します

この方法でコピーできるデータ量には制限がありますか?通常のCtrl + Cは同じ制限を受けていないようです。

注:誰かがこれをDoes document.execCommand('copy') have a size limitation?の可能な複製としてマークしました。似たような質問かもしれませんが、私が使用していない特定のフレームワークとしてタグ付けされており、答えられていませんでした。私は私の質問がより一般的であり、なおも適切であると信じています。

参考のためにコードを添付します。

 function copyTextToClipboard(text) { 
     var textArea = document.createElement('textarea'); 
     textArea.style.position = 'fixed'; 
     textArea.style.top = 0; 
     textArea.style.left = 0; 
     textArea.style.width = '2em'; 
     textArea.style.height = '2em'; 
     textArea.style.padding = 0; 
     textArea.style.border = 'none'; 
     textArea.style.outline = 'none'; 
     textArea.style.boxShadow = 'none'; 
     textArea.style.background = 'transparent'; 
     textArea.value = text; 
     document.body.appendChild(textArea); 
     textArea.select(); 
     try { 
      var successful = document.execCommand('copy'); 
      var msg = successful ? 'successful' : 'unsuccessful'; 
      console.log('Copying text command was ' + msg); 
     } catch (err) { 
      console.log('Oops, unable to copy'); 
     } 
     document.body.removeChild(textArea); 
     } 
+0

の可能性のある重複〔んdocument.execCommand( 'コピー')はサイズの制限がありますか?](https://stackoverflow.com/questions/43641182/does-document-execcommandcopy-サイズ制限あり) –

+1

編集を参照してください。その質問は解決されなかった。 –

答えて

4

問題は、それがexecCommand('copy')呼び出し自体よりも、この長いテキストを描画するのにかかる時間で行うことがより多くを持っています。

document.execCommand(「カット」/「コピー」)それは短いランニングのユーザーが生成したイベントハンドラ内から呼び出されていなかったため拒否されました:

Firefoxはかなり説明エラーメッセージを発生させます。

あなたのコードは、テキストを生成するために時間がかかりすぎるため、ブラウザはとしてそれを認識していない半信頼さイベント...

ソリューションは、最初にこのテキストを生成するために、その後で、ユーザージェスチャーを聞いた後で、execCommandに電話をかけてください。したがって、可能にするには、たとえば次のようにします。 mousedownイベントを聞いてテキストを生成し、実際にはmouseupイベントでのみcopyコマンドを実行します。

const text = ('some text a bit repetitive ' + Date.now()).repeat(50000); 
 

 
function copyTextToClipboard(text) { 
 
    // first we create the textArea 
 
    var textArea = document.createElement('textarea'); 
 
    textArea.style.position = 'absolute'; 
 
    textArea.style.opacity = '0'; 
 
    textArea.value = text; 
 
    document.body.appendChild(textArea); 
 

 
    var execCopy = e => { // triggered on mouseup 
 
    textArea.select(); 
 
    var successful = document.execCommand('copy'); 
 
    var msg = successful ? 'successful' : 'unsuccessful'; 
 
    console.log('Copying text command was ' + msg); 
 
    document.body.removeChild(textArea); 
 
    }; 
 
    // here the magic 
 
    btn.addEventListener('mouseup', execCopy, { 
 
    once: true 
 
    }); 
 
} 
 
// triggered on mousedown 
 
btn.onmousedown = e => copyTextToClipboard(text);
<button id="btn">copy some text in your clipboard</button> 
 
<p>May struggle your browser a little bit, it's quite a long text... Please be patient</p>

関連する問題