| 1 | export function addBlankTargetsToLinks(str) { |
| 2 | const doc = new DOMParser().parseFromString(str, "text/html"); |
| 3 | |
| 4 | doc.querySelectorAll("a").forEach((anchor) => { |
| 5 | const href = anchor.getAttribute("href") || ""; |
| 6 | if ( |
| 7 | href.startsWith("#") || |
| 8 | href.trim().toLowerCase().startsWith("javascript") |
| 9 | ) { |
| 10 | return; |
| 11 | } |
| 12 | |
| 13 | if ( |
| 14 | !anchor.hasAttribute("target") || |
| 15 | anchor.getAttribute("target") === "" |
| 16 | ) { |
| 17 | anchor.setAttribute("target", "_blank"); |
| 18 | } |
| 19 | |
| 20 | const rel = (anchor.getAttribute("rel") || "").split(/\s+/).filter(Boolean); |
| 21 | if (!rel.includes("noopener")) rel.push("noopener"); |
| 22 | if (!rel.includes("noreferrer")) rel.push("noreferrer"); |
| 23 | anchor.setAttribute("rel", rel.join(" ")); |
| 24 | }); |
| 25 | |
| 26 | return doc.body.innerHTML; |
| 27 | } |