使用javascript innerHTML清理注入的html?

时间:2017-09-20 11:02:21

标签: javascript html sanitization html-sanitizing

需要修复下面的函数以在listStr内部清理html,尝试了各种HTML转义函数(listDom.innerHTML = escapeHTML(listStr);)但是我将原始文本作为输出而不是元素!!

    function createList(list) {
        let listStr = "";

        list.forEach(function (item) {

            if (item.click) {
                var clean_url = encodeURIComponent(item.href);
                clean_url = "";
                //console.log(clean_url);
                listStr += `<div class='list_item' id="${item.uid}"><a href="javascript:void(0);">${item.label}</a></div>`;

            } else {
                //'loop', i + ''
                listStr += `<div class='list_item' id="${item.uid}" loop="${item.loop}"><a href="${item.href}">${item.label}</a></div>`;
            }
        });

        listStr += '';

        let listDom = document.createElement("div");
        listDom.setAttribute("id", "list");
        listDom.setAttribute("style", "display: none;");
        listDom.innerHTML = listStr;

        return listDom;
    }

1 个答案:

答案 0 :(得分:0)

我最终这样做了:

                let listItem = document.createElement('div');
                listItem.setAttribute('class', 'list_item');
                listItem.setAttribute('id', item.uid);

                let linkItem  = document.createElement('a');
                linkItem.setAttribute('href', 'javascript:void(0);');
                linkItem.innerText = item.label;

                listItem.appendChild(linkItem);
                listStr.appendChild(listItem);