* 创建安全的 DOM 节点 * @param {string} tag - 标签名 * @param {Object} attributes - 属性对象 * @param {string|HTMLElement[]} children - 子元素 * @returns {HTMLElement}
(tag, attributes = {}, children = [])
| 128 | * @returns {HTMLElement} |
| 129 | */ |
| 130 | static createElement(tag, attributes = {}, children = []) { |
| 131 | const element = document.createElement(tag); |
| 132 | |
| 133 | // 设置属性(自动转义) |
| 134 | Object.entries(attributes).forEach(([key, value]) => { |
| 135 | // 禁止设置事件处理器 |
| 136 | if (key.startsWith('on')) { |
| 137 | console.warn(`[HTMLSanitizer] Blocked event handler: ${key}`); |
| 138 | return; |
| 139 | } |
| 140 | |
| 141 | // 转义属性值 |
| 142 | element.setAttribute(key, this.escapeAttr(value)); |
| 143 | }); |
| 144 | |
| 145 | // 添加子元素 |
| 146 | const childArray = Array.isArray(children) ? children : [children]; |
| 147 | childArray.forEach(child => { |
| 148 | if (typeof child === 'string') { |
| 149 | element.appendChild(document.createTextNode(child)); |
| 150 | } else if (child instanceof HTMLElement) { |
| 151 | element.appendChild(child); |
| 152 | } |
| 153 | }); |
| 154 | |
| 155 | return element; |
| 156 | } |
| 157 | |
| 158 | /** |
| 159 | * 验证 URL 安全性 |
no test coverage detected