UNPKG

jodit

Version:

Jodit is an awesome and useful wysiwyg editor with filebrowser

85 lines (84 loc) 2.72 kB
/*! * Jodit Editor (https://xdsoft.net/jodit/) * Released under MIT see LICENSE.txt in the project root for license information. * Copyright (c) 2013-2026 Valerii Chupurnov. All rights reserved. https://xdsoft.net */ /** * @module helpers/html */ import { Dom } from "../../dom/dom.js"; import { $$, attr } from "../utils/index.js"; /** * Removes dangerous constructs from HTML */ export function safeHTML(box, options) { var _a; if (!Dom.isElement(box) && !Dom.isFragment(box)) { return; } const removeEvents = (_a = options.removeEventAttributes) !== null && _a !== void 0 ? _a : options.removeOnError; if (removeEvents) { removeAllEventAttributes(box); $$('*', box).forEach(elm => removeAllEventAttributes(elm)); } else if (options.removeOnError) { sanitizeHTMLElement(box, options); $$('[onerror]', box).forEach(elm => sanitizeHTMLElement(elm, options)); } if (options.safeJavaScriptLink) { sanitizeHTMLElement(box, options); $$('a[href^="javascript"]', box).forEach(elm => sanitizeHTMLElement(elm, options)); } if (options.safeLinksTarget) { $$('a[target="_blank"]', box).forEach(elm => { const rel = elm.getAttribute('rel') || ''; const parts = rel.split(/\s+/).filter(Boolean); if (!parts.includes('noopener')) { parts.push('noopener'); } if (!parts.includes('noreferrer')) { parts.push('noreferrer'); } attr(elm, 'rel', parts.join(' ')); }); } } /** * Remove all on* event handler attributes from an element */ function removeAllEventAttributes(elm) { if (!Dom.isElement(elm)) { return false; } let effected = false; const toRemove = []; for (let i = 0; i < elm.attributes.length; i++) { if (elm.attributes[i].name.toLowerCase().startsWith('on')) { toRemove.push(elm.attributes[i].name); } } for (const name of toRemove) { elm.removeAttribute(name); effected = true; } return effected; } export function sanitizeHTMLElement(elm, { safeJavaScriptLink, removeOnError } = { safeJavaScriptLink: true, removeOnError: true }) { if (!Dom.isElement(elm)) { return false; } let effected = false; if (removeOnError && elm.hasAttribute('onerror')) { attr(elm, 'onerror', null); effected = true; } const href = elm.getAttribute('href'); if (safeJavaScriptLink && href && href.trim().indexOf('javascript') === 0) { attr(elm, 'href', location.protocol + '//' + href); effected = true; } return effected; }