Вы можете безопасно скрыть теги html с помощью атрибута iframe sandbox .
Идея здесь заключается в том, что вместо того, чтобы пытаться повторно использовать нашу строку, мы используем собственный синтаксический анализатор браузера путем вставки текста в элемент DOM и последующего запроса свойства textContent
/ innerText
этого элемента.
Самый подходящий элемент, в который нужно добавить наш текст, представляет собой изолированный iframe, так что мы можем (g1] XSS ).
Недостатком этого подхода является то, что он работает только в браузерах.
Вот что я пришел (не проверено на битву):
const stripHtmlTags = (() => {
const sandbox = document.createElement("iframe");
sandbox.sandbox = "allow-same-origin"; // <--- This is the key
sandbox.style.setProperty("display", "none", "important");
// Inject the sanbox in the current document
document.body.appendChild(sandbox);
// Get the sandbox's context
const sanboxContext = sandbox.contentWindow.document;
return (untrustedString) => {
if (typeof untrustedString !== "string") return "";
// Write the untrusted string in the iframe's body
sanboxContext.open();
sanboxContext.write(untrustedString);
sanboxContext.close();
// Get the string without html
return sanboxContext.body.textContent || sanboxContext.body.innerText || "";
};
})();
Использование ( demo ):
console.log(stripHtmlTags(`XSS injection :)`));
console.log(stripHtmlTags(`