2024-08-23 03:51:09 +00:00
|
|
|
import createDOMPurifier from 'dompurify';
|
2023-03-22 13:48:50 +00:00
|
|
|
|
2024-08-23 03:51:09 +00:00
|
|
|
export function sanitizeHTML(source: string | Node): string {
|
|
|
|
return defaultPurifier.sanitize(source);
|
|
|
|
}
|
|
|
|
|
|
|
|
export function sanitizeTutorialHTML(source: string | Node): string {
|
|
|
|
return tutorialPurifier.sanitize(source, {
|
|
|
|
ADD_TAGS: ['iframe'],
|
|
|
|
ADD_ATTR: ['allowFullscreen'],
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
const defaultPurifier = createDOMPurifier();
|
|
|
|
defaultPurifier.addHook('uponSanitizeAttribute', handleSanitizeAttribute);
|
2023-03-22 13:48:50 +00:00
|
|
|
|
2024-08-23 03:51:09 +00:00
|
|
|
const tutorialPurifier = createDOMPurifier();
|
|
|
|
tutorialPurifier.addHook('uponSanitizeAttribute', handleSanitizeAttribute);
|
|
|
|
tutorialPurifier.addHook('uponSanitizeElement', handleSanitizeTutorialElement);
|
|
|
|
|
|
|
|
function handleSanitizeAttribute(node: Element) {
|
2023-03-22 13:48:50 +00:00
|
|
|
if (!('target' in node)) { return; }
|
|
|
|
|
|
|
|
node.setAttribute('target', '_blank');
|
2024-08-23 03:51:09 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
function handleSanitizeTutorialElement(node: Element, data: createDOMPurifier.SanitizeElementHookEvent) {
|
2023-03-22 13:48:50 +00:00
|
|
|
if (data.tagName !== 'iframe') { return; }
|
|
|
|
|
|
|
|
const src = node.getAttribute('src');
|
|
|
|
if (src?.startsWith('https://www.youtube.com/embed/')) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2024-08-23 03:51:09 +00:00
|
|
|
node.parentNode?.removeChild(node);
|
2023-03-22 13:48:50 +00:00
|
|
|
}
|