LoginSignup
2
2

More than 3 years have passed since last update.

javascriptで任意の文字列をクリップボードにコピーしたいとき

Last updated at Posted at 2019-07-06

自分用のメモ。

code

copy.js
function copyCode(targetEl) {
  if (document.queryCommandSupported('copy')) {  // ①
    const range = document.createRange();
    range.selectNodeContents(targetEl);
    window.getSelection().empty();    // ②
    window.addRange(range);
    document.execCommand("copy");
  }
  else {
    alert('un supported');
  }
}

const btn = document.querySelector(".btn");
btn.addEventListener("click", () => copyCode(el));

point

①:サポートしているかどうかで、処理を分ける。クリップボードへのアクセス・コピー処理は比較的新しい機能のようなので、レガシー対応している場合は必要。なお、 queryCommandSupported は全ブラウザバージョン対応しているとのこと(参照:https://caniuse.com/#search=queryCommandSupported)

②: .empty は基本必要ないと思われる。なぜ書いているかというと、 buttona など、クリックされることを前提としている要素以外にclickイベントを登録した場合に、 .empty を書かないとコピーできない。理由は分かっていないので、詳しい人がいたら教えてください。m(_ _)m

supoprt
pc

IE9~

mobile

ios 10.0~
androind 4.2~
https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand

2
2
0

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
2
2