WebSurfer's Home

トップ > Blog 1   |   ログイン
APMLフィルター

JavaScript で Html Escape

by WebSurfer 2021年5月18日 11:25

ユーザー入力文字列のサニタイジング(無害化)のためのエスケープ処理を JavaScript で行うためのコードを備忘録として書いておきます。以下のコードは ES6 をサポートしてない IE11 でも動くことは確認しました。

<script type="text/javascript">
    //<![CDATA[

    function htmlEscape(str) {
        if (!str) return;
        return str.replace(/[<>&"'`]/g, function (match) {
            const escape = {
                '<': '&lt;',
                '>': '&gt;',
                '&': '&amp;',
                '"': '&quot;',
                "'": '&#39;',
                '`': '&#x60;'
            };
            return escape[match];
        });
    }

    // 以下は検証用
    var str = '& < > ` " ' + "'";
    console.log(htmlEscape(str));

    // 結果 (IE11 も同様):
    // &amp; &lt; &gt; &#x60; &quot; &#39;

    //]]>
</script>

そんな情報はググればすぐ出てくると言われるかもしれませんが、基本的にネットの記事は自分で検証して確認するまで信用できない疑り深い性格なものですから。(笑)

クロスサイトスクリプティング(XSS)対策の一つに、ユーザー入力文字列のサニタイジング(無害化)がありますが、その目的で上記コードは文字列内の < > & " ' ` の 6 文字を &lt; &gt; &amp; &quot; &#39; &#x60; にエスケープ(変換)しています。

ASP.NET MVC などではフレームワーク組み込みでサニタイジング機能が含まれていますので、Html ヘルパーや Tag ヘルパーを使っている限り上のスクリプトの使い道はないです。

では、どういうときに使うかと言うと、例えば以下のように、Web API などから取得した文字列で html ソースを組み立てる場合でしょうか。

function getCars() {
  $.ajax({
    type: "POST", 
    url: "Api/GetCarsByDoors", 
    data: '{"doors":' + $("#ddlDoors").val() + '}', 
    contentType: "application/json; charset=utf-8",
 
    success: function (cars) {      
      $('#output').empty();
      $.each(cars, function (index, car) {
        $('#output').append(
          '<p><strong>' + car.Make + ' ' +
          car.Model + '</strong><br />Description: ' +
          htmlEscape(car.Description) + '</p>');
        });
      }
  });
}

Tags: , ,

JavaScript

About this blog

2010年5月にこのブログを立ち上げました。主に ASP.NET Web アプリ関係の記事です。

Calendar

<<  2024年4月  >>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

View posts in large calendar