79612789

Date: 2025-05-08 16:12:53
Score: 0.5
Natty:
Report link

I implemented one solution HTML doesn't include target="_blank" on the anchor tags.

so, we need to ensure all anchor tags in the HTML string have target="_blank" and optionally rel="noopener noreferrer" added to them before rendering.

function addTargetBlank(htmlString) {
  const parser = new DOMParser();
  const docData = parser.parseFromString(htmlString, 'text/html');

  const links = docData.querySelectorAll('a[href]');
  links.forEach(link => {
    link.setAttribute('target', '_blank');
    link.setAttribute('rel', 'noopener noreferrer');
  });

  return docData .body.innerHTML;
}`enter code here`

const Html = addTargetBlank(rawHtmlString);
const showNewHtml = DOMPurify.sanitize(newHtml );
Reasons:
  • Long answer (-0.5):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (1):
Posted by: Anurag Singh