LoginSignup
6

More than 3 years have passed since last update.

posted at

【JavaScript】URLをコピーするボタンを作る

概要

URLをコピーするボタンをJavaScriptで実装する。
実装はとっても簡単なのでサクッと書きます。

実装(html)

<button onclick="copyUrl()">Copy URL</button>

実装(JavaScript)

function copyUrl() {
    const element = document.createElement('input');
    element.value = location.href;
    document.body.appendChild(element);
    element.select();
    document.execCommand('copy');
    document.body.removeChild(element);
}

URLをコピーするにはテキストボックスを用意し、そこにURL(location.href)を設定します。
テキストボックスをDOMに追加した後、 select() で設定したURLを選択した状態にします。

document.execCommand('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
What you can do with signing up
6