javascript ペーストイベントを取得する

javascript ペーストイベントを取得する

javascriptで、addEventListenerを使用して、ペースト(貼り付け)イベントを取得するサンプルコードを記述してます。

環境

  • OS windows10 pro 64bit
  • Apache 2.4.43
  • ブラウザ chrome 104.0.5112.101

ペーストイベント取得

IEは取得方法が異なりますが、「EventListener」に「paste」イベントを登録して取得します。

<input type="text" value="">

<script>

    // ペーストイベント
    document.addEventListener("paste", (e) => {

        let result;

        if (e.clipboardData && e.clipboardData.getData) {

            result = e.clipboardData.getData('text/plain');

        } else if (window.clipboardData && window.clipboardData.getData) {
            /** IEの場合 */
            result = window.clipboardData.getData('Text');

        }

        console.log(result);

    });

</script>

実行結果

サンプルコード

以下は、
ペースト(貼り付け)を行うと、貼り付けた内容をテキストエリアに出力する
サンプルコードとなります。

※cssには「bootstrap5」を使用してます。「bootstrap5」は、IEのサポートを終了してます。関数はアロー関数化してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700|Material+Icons">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css">
</head>

<style>
  .main {
    margin: 0 auto;
    margin-top: 200px;
    display: flex;
    flex-direction: column;
    align-items: center;
    font-size: 30px;
  }
</style>
<script>

  window.onload = () => {
    // ペーストイベント
    document.addEventListener("paste", (e) => {

      let result;

      if (e.clipboardData && e.clipboardData.getData) {

        result = e.clipboardData.getData('text/plain');

      } else if (window.clipboardData && window.clipboardData.getData) {
        /** IEの場合 */
        result = window.clipboardData.getData('Text');
      }
      txtarea.value = result;
    });

  }

</script>

<body>

  <div class="main container">
    <div class="mb-3">
      <label for="exampleFormControlTextarea1" class="form-label">ペースト結果を表示</label>
      <textarea id="txtarea" class="form-control" rows="10"></textarea>
    </div>
  </div>

</body>

</html>

貼り付けした結果が表示されていることが確認できます。