js セキュアコーディング? エスケープ処理をいれたい

作成日:2025-10-21, 更新日:2026-01-05

概要

セキュアコーディング・・・変数を使うとき、悪いことをされないようにエスケープ処理をしっかりしましょう・・・ってヤツをしたい

やりたいこと

下記のような感じでJavascriptでHTMLタグを作りたい

function xxx(prms) {
    let html = 'xxxx';
    return html;
}

HTMLタグの作成とエスケープ処理

方法はざっくりと4つ、他にあるかもしれない

  • 変数にすべてHTMLタグをセット
  • HTMLタグをcreateElement()で作成
  • 変数に基本になるHTMLタグをセット
  • templateタグなどに追加し、querySelector()で取得

変数にすべてHTMLタグをセット

変数にセットするときにエスケープ処理をする

function xxx(prms) {
    let html = `<a href="${html_escape(prms.xxx)}"></a>`;
    return html;
}
element.innerHTML = xxx(prms)

HTMLタグをcreateElement()で作成

タグを作って値をセットしていく
html構造が複雑だと可読性は悪い
setAttribute()などがエスケープ処理を内包しているのでそれ以上、気にする必要がない

function xxx(prms) {
    const html = document.createElement('a');
    html.setAttribute('href', prms.xxx);
    return html;
}
parentElement.appendChild(xxx(prms));

変数に基本になるHTMLタグをセット

雛形になるHTMLを変数にセットし、値をセットしていく
setAttribute()などがエスケープ処理を内包しているのでそれ以上、気にする必要がない

function xxx(prms) {
    const htmlString = `<a href="#"></a>`;
    const tempDiv = document.createElement('div');
    tempDiv.innerHTML = `${htmlString }`;
    const html = tempDiv.firstChild; // 一つ目の子要素をセット
    html.setAttribute('href', prms.xxx);
    return html;
}
parentElement.appendChild(xxx(prms));

templateタグなどに追加し、querySelector()で取得

雛形になるHTMLをtemplateタグなどを使って、HTMLに記載しておく
templateタグを取得し、値をセットしていく
setAttribute()などがエスケープ処理を内包しているのでそれ以上、気にする必要がない

function xxx(prms) {
    const template = document.querySelector('template[id=xxx]');
    const fragment = template.content.cloneNode(true); // テンプレートの複製
    const html = fragment.querySelector('a');
    if (html) {
        html.setAttribute('href', prms.xxx);
    }
    return html;
}
parentElement.appendChild(xxx(prms));