LoginSignup
14

More than 5 years have passed since last update.

JavaScript でクリップボードに文字列をコピーさせる

Last updated at Posted at 2016-11-17

document.execCommand('copy') を使う。

雑にこんな感じ

// elementはinput要素とか
function copy(element){

  // コピーさせたいテキストの選択
  element.focus();
  element.setSelectionRange(0, 9999);

  // クリップボードにコピー
  document.execCommand('copy');

  // コピーさせたいテキストの選択を解除
  element.blur();
}

element.focus()のとこ、特にスマホだと一瞬ソフトウェアキーボードが出てきてダサいです。多分もっといい方法がある

MDNの該当ページにもブラウザのサポート状況が書いてあるけど、スマホの対応は雑にこんな感じ。新しいブラウザだとだいたい使えるっぽい。

  • iOS10 Safari 可
  • iOS9 Safari 不可
  • Android 標準ブラウザ 不可
  • Android Chrome 可
  • PhantomJS 不可

そのブラウザがコマンドを実行可能かは document.queryCommandSupported で判定可能。

if (document.queryCommandSupported('copy')) {
  // コピーボタンを描画する処理とか
}

参考ページ

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14