LoginSignup
4
1

Webページ上に貼り付けられたクリップボードの内容を読み取る2つの方法

Last updated at Posted at 2023-11-30

概要

Webページ上に貼り付けられたクリップボードの内容を読み取るとき,

  • Clipboard.readText() を使用する方法
  • ClipboardEvent.clipboardData.getData(format) を使用する方法

がある.Clipboard.readText() を使用するには権限APIclipboard-read 権限が必要だが,ClipboardEvent.clipboardData.getData(format) の使用に権限は必要ない.

詳細

以下,それぞれの実装例を示す.

Clipboard.readText()

readtext.html
<label for="editor">右の入力欄にテキストを貼り付けてみてください。</label>
<input id="editor" type="text" />

<h3>ログ:</h3>
<p id="log"></p>

<script>
    async function logPaste(event) {
        let pastedText = "";
        await navigator.clipboard.readText()
                           .then(text => {
                            pastedText = text;
                           });
        log.innerText = `貼り付けされました: ${pastedText}\n${log.innerText}`;
    }

    const editor = document.getElementById("editor");
    const log = document.getElementById("log");

    editor.onpaste = logPaste;
</script>

readtext.html を開き,入力欄に何らかのテキストを貼り付けると,clipboard-read 権限を要求するダイアログが表示される(以下の画像はGoogle Chromeでの表示例).

clipboard-read

「許可する」をクリックするとクリップボードの読み取りが完了し,結果が画面に表示される.

実行結果

ClipboardEvent.clipboardData.getData(format)

getdata.html
<label for="editor">右の入力欄にテキストを貼り付けてみてください。</label>
<input id="editor" type="text" />

<h3>ログ:</h3>
<p id="log"></p>

<script>
    function logPaste(event) {
        const pastedText = event.clipboardData.getData("text");
        log.innerText = `貼り付けされました: ${pastedText}\n${log.innerText}`;
    }

    const editor = document.getElementById("editor");
    const log = document.getElementById("log");

    editor.onpaste = logPaste;
</script>

同じように getdata.html を開き,入力欄に何らかのテキストを貼り付けると,今度はダイアログが表示されずにクリップボードの読み取りが完了する.

なぜ Clipboard.readText() には権限が要求されるのか

HTMLファイル中のJavaScript部分をよく見ると,readtext.html では event(pasteイベント)を利用していない.つまり,Clipboard.readText()pasteイベントなどとは無関係にクリップボードの値を取得できる.一方,ClipboardEvent.clipboardData.getData(format) はpasteイベントが発生しない限り,クリップボードは取得されない.この違いが,権限の要求有無に影響していると考えられる.

参考

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