1
1

http環境(非https)でのクリップボードへのコピー【JavaScript/TypeScript】

Last updated at Posted at 2023-11-22

はじめに

偉大なる本家様は以下になります。
この記事は、以下のページで紹介されているjQueryのコードをTypeScript(+α)に書き換えた記事です。

概要

JavaSciptでクリップボードへコピーする際、 navigator.clipboard[1] を利用することで実現出来ます。
しかしながら、http環境では動作しません。
そこで、 http環境でも動作するdocument.execCommand[2] を利用したコピー方法をフォールバックとして利用します。

このフォールバックなコピーコードが以下になります。

コード

const initCopyActions = () => {
    // コピーする際に押すボタン(id="copy-button"の場合)
    const copyButton = document.getElementById('copy-button');
    
    // http環境で動くコピーコード
    const copyTextFallback = (str: string): string => {
        if (!str || typeof str !== 'string') {
            return '';
        }
        const textarea = document.createElement('textarea');
        textarea.id = 'tmp_copy';
        textarea.style.position = 'fixed';
        textarea.style.right = '100vw';
        textarea.style.fontSize = '16px';
        textarea.setAttribute('readonly', 'readonly');
        textarea.textContent = str;
        document.body.appendChild(textarea);
        const elm = document.getElementById('tmp_copy') as HTMLTextAreaElement;
        elm.select();
        const range = document.createRange();
        range.selectNodeContents(elm);
        const sel = window.getSelection();
        if (sel) {
            sel.removeAllRanges();
            sel.addRange(range);
        }
        elm.setSelectionRange(0, 999999);
        document.execCommand('copy');
        document.body.removeChild(textarea);
    
        return str;
    };
    
    // メインのコピーコード
    const copyTemplate = (copyText: string, targetText: string) => {
        if (!navigator.clipboard) {
            // navigator.clipboardが利用的出来ない場合は、フォールバックなコードを実行
            copyTextFallback(copyText);
            alert(`${targetText}をコピーしました。`);
            return;
        }
        // https環境で動作するコード
        navigator.clipboard.writeText(copyText).then(
            () => {
                alert(`${targetText}をコピーしました。`);
            },
            () => {
                alert('コピーに失敗しました。');
            }
        );
    };
    
    // コピーコードを実行するコード
    const copyEmailToClipboard = () => {
        copyTemplate('aiueo@gmail.com', 'メールアドレス');
    };
    
    // イベントハンドラ
    copyButton?.addEventListener('click', copyEmailToClipboard);
};

結果

以下のようにダイアログが表示され、クリップボードへ aiueo@gmail.com がコピーされます。

image.png

リンク

[1] MDN: Navigator: clipboard プロパティ
[2] MDN: Document: execCommand() メソッド

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