From 7aa82bb9d4d4092bffbef0fb874bda36968df5ae Mon Sep 17 00:00:00 2001 From: 7w1 Date: Thu, 30 Apr 2026 00:43:12 -0500 Subject: [PATCH] always open links in new tab --- src/app/components/editor/output.ts | 4 ++-- src/app/plugins/markdown/markdownToHtml.ts | 11 ++++++++++- src/app/plugins/react-custom-html-parser.tsx | 7 ++++++- 3 files changed, 18 insertions(+), 4 deletions(-) diff --git a/src/app/components/editor/output.ts b/src/app/components/editor/output.ts index e52f99c06..11548cbb6 100644 --- a/src/app/components/editor/output.ts +++ b/src/app/components/editor/output.ts @@ -98,7 +98,7 @@ const elementToCustomHtml = ( } const matrixTo = `https://matrix.to/#/${fragment}`; - return `${sanitizeText(node.name)}`; + return `${sanitizeText(node.name)}`; } case BlockType.Emoticon: return node.key.startsWith('mxc://') @@ -107,7 +107,7 @@ const elementToCustomHtml = ( )}" title="${sanitizeText(node.shortcode)}" height="32" />` : sanitizeText(node.key); case BlockType.Link: - return `${children}`; + return `${children}`; case BlockType.Command: return `/${sanitizeText(node.command)}`; default: diff --git a/src/app/plugins/markdown/markdownToHtml.ts b/src/app/plugins/markdown/markdownToHtml.ts index e597e61a6..802057883 100644 --- a/src/app/plugins/markdown/markdownToHtml.ts +++ b/src/app/plugins/markdown/markdownToHtml.ts @@ -61,7 +61,14 @@ export function markdownToHtml(markdown: string): string { // Unescape inline sequences (e.g., \*, \_) after parsing const unescapedInline = unescapeMarkdownInlineSequences(html); - // Sanitize using DOMPurify, restricting to Matrix-spec allowed HTML tags/attributes + // Force all links to open in a new tab + DOMPurify.addHook('afterSanitizeAttributes', (node) => { + if (node.tagName === 'A' && node.getAttribute('href')) { + node.setAttribute('target', '_blank'); + node.setAttribute('rel', 'noreferrer noopener'); + } + }); + const sanitized = DOMPurify.sanitize(unescapedInline, { ALLOWED_TAGS: [ 'h1', @@ -125,5 +132,7 @@ export function markdownToHtml(markdown: string): string { ALLOWED_URI_REGEXP: /^(?:https?|ftp|mailto|magnet|mxc):/i, }); + DOMPurify.removeHook('afterSanitizeAttributes'); + return sanitized; } diff --git a/src/app/plugins/react-custom-html-parser.tsx b/src/app/plugins/react-custom-html-parser.tsx index a0ed74018..0c54a08b9 100644 --- a/src/app/plugins/react-custom-html-parser.tsx +++ b/src/app/plugins/react-custom-html-parser.tsx @@ -250,7 +250,11 @@ export const factoryRenderLinkifyWithMention = ( } } - return {content}; + return ( + + {content} + + ); }; return renderLink; @@ -629,6 +633,7 @@ export const getReactCustomHtmlParser = ( const renderedChildren = renderChildren(); const anchorProps = { ...props, + target: '_blank', rel: ensureNoopenerRel(props.rel), };