LoginSignup
0
0

More than 1 year has passed since last update.

【2023】JavaScriptでクリップボードのコピーをする方法

Last updated at Posted at 2023-02-24

こんにちは!普段はTK:Re GAMESというゲームブログを書いているTKです!
現在WordPressの自作テーマを作っており、その過程で調べたことを記事にしていこうかと思いますのでよろしくおねがいします!

非推奨の書き方

さて、今回はJavaScriptでクリップボードのコピーをする方法についてです。
クリップボードのコピーといえばこちらの方法を思い浮かべる方が多いのではないでしょうか?

const text = document.getElementsByTagName("textarea")[0];
// 文字をすべて選択
text.select();
// クリップボードにコピー
document.execCommand("copy");

ネットで調べると上記の方法が多く出てくるのですが、実は2023年現在非推奨になっており今後削除される可能性があるとのことでした。
https://developer.mozilla.org/ja/docs/Web/API/Document/execCommand

なので可能であれば以下の方法に切り替えましょう。

今後はnavigator.clipboardを使った書き方へ

今後クリップボード周りに関してはexecCommandのに代わりnavigator.clipboardが使われるようになります。
具体的な使用例は以下になります。

const text = document.getElementsByTagName("textarea")[0];
// クリップボードにコピー
navigator.clipboard.writeText(text);

注意点

navigator.clipboardの使用に関してですが、2点注意点があります。
1.https環境のみ使用可能
2.文字列ではなくDOMに使用

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