[JavaScript] 表示いるページURLなど特定文字コピーさせる方法

2 min read
hiroweb developer

背景

ブログの記事などの URL をコピーさせるための機能が欲しい。

方法

textareainputなどのテキストを入力できる要素に入力されている値をdocument.execCommand("copy")を使うと、クリップボードに書き込むことができる。

大まかな copy の仕方は下記の通り。

const textarea = document.querySelector("textarea");
textarea.select();
document.execCommand("copy");

実例

// クリックしたらコピーさせるボタン
const button = document.querySelector("button");

button.addEventListener("click", (e) => {
  e.preventDefault();

  // 入力要素を作る
  const input = document.createElement("input");
  // 入力要素に表示中のURLを挿入する
  input.value = location.href;
  // DOM上に入力要素を挿入する
  document.body.appendChild(input);
  // 入力した文字を選択する
  input.select();
  // クリップボードに書き込む
  document.execCommand("copy");
  // 要素を削除する
  input.remove();
});

記事の URL なので、location.hrefを使用しているが、input.valueに入れる値は任意のもので良い。

サンプル