自分用のメモ。
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
は基本必要ないと思われる。なぜ書いているかというと、 button
や a
など、クリックされることを前提としている要素以外に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