add open message links in a new window (#543)

* add open message links in a new window Added addBlankTargetsToLinks(str) to webui/js/messages.js, which adds target='_blank' attribute to message links during rendering, while maintaining security practices such as setting noopener and norefferer relation * add export addBlankTargetsToLinks()

Mustafa Mohsen committed Jul 12, 2025 at 14:12 UTC e585fc075b9b29734078e4ec28c4d2958092f639
1 file changed +17
webui/js/messages.js
+17
@@ -197,6 +197,7 @@ export function _drawMessage(
197 processedContent = convertImgFilePaths(processedContent);
198 processedContent = marked.parse(processedContent, { breaks: true });
199 processedContent = convertPathsToLinks(processedContent);
200 + processedContent = addBlankTargetsToLinks(processedContent);
201 spanElement.innerHTML = processedContent;
202
203 // KaTeX rendering for markdown
@@ -247,6 +248,22 @@ export function _drawMessage(
248 return messageDiv;
249 }
250
251 +export function addBlankTargetsToLinks(str) {
252 + const doc = new DOMParser().parseFromString(str, 'text/html');
253 +
254 + doc.querySelectorAll('a').forEach(anchor => {
255 + if (!anchor.hasAttribute('target') || anchor.getAttribute('target') === '') {
256 + anchor.setAttribute('target', '_blank');
257 + }
258 +
259 + const rel = (anchor.getAttribute('rel') || '').split(/\s+/).filter(Boolean);
260 + if (!rel.includes('noopener')) rel.push('noopener');
261 + if (!rel.includes('noreferrer')) rel.push('noreferrer');
262 + anchor.setAttribute('rel', rel.join(' '));
263 + });
264 + return doc.body.innerHTML;
265 +}
266 +
267 export function drawMessageDefault(
268 messageContainer,
269 id,