From d88f785cd99c43b251704d11709f119259b89fc6 Mon Sep 17 00:00:00 2001 From: Martin Stone Date: Wed, 16 Apr 2025 10:47:47 -0400 Subject: [PATCH] fix confluence links to open in new tab, improve rendering --- .../src/components/PageContent.tsx | 96 +++++++++++++++++++ plugins/confluence-plugin/src/hooks.tsx | 6 +- .../confluence-plugin/src/mocks/mockBodies.ts | 2 +- 3 files changed, 100 insertions(+), 4 deletions(-) diff --git a/plugins/confluence-plugin/src/components/PageContent.tsx b/plugins/confluence-plugin/src/components/PageContent.tsx index 278a3b8..0a302a9 100644 --- a/plugins/confluence-plugin/src/components/PageContent.tsx +++ b/plugins/confluence-plugin/src/components/PageContent.tsx @@ -17,6 +17,89 @@ import { import "../baseStyles.css"; +const addTargetBlank = (htmlString: string): string => { + try { + const parser = new DOMParser(); + const doc = parser.parseFromString(htmlString, "text/html"); + + doc.querySelectorAll("a").forEach((link) => { + link.setAttribute("target", "_blank"); + }); + + return doc.body.innerHTML; + } catch (error) { + console.error("Error parsing HTML string in addTargetBlank:", error); + return htmlString; + } +}; + +const makeLinksAbsolute = (htmlString: string, host: string): string => { + try { + const parser = new DOMParser(); + const doc = parser.parseFromString(htmlString, "text/html"); + + // Loop over all tags + doc.querySelectorAll("a").forEach((link) => { + const href = link.getAttribute("href"); + if (href) { + // Check if the link is relative by testing for absolute URL prefixes + if (!href.match(/^https?:\/\//) && !href.startsWith("//")) { + // Create an absolute URL by resolving against the provided host + const absoluteUrl = new URL(href, host).href; + link.setAttribute("href", absoluteUrl); + } + } + }); + + // Loop over all tags + doc.querySelectorAll("img").forEach((img) => { + const src = img.getAttribute("src"); + if (src) { + // Check if the src is relative by testing for absolute URL prefixes + if (!src.match(/^https?:\/\//) && !src.startsWith("//")) { + // Create an absolute URL by resolving against the provided host + const absoluteUrl = new URL(src, host).href; + img.setAttribute("src", absoluteUrl); + } + } + }); + // Loop over all tags + doc.querySelectorAll("link").forEach((link) => { + const href = link.getAttribute("href"); + if (href) { + // Check if the href is relative by testing for absolute URL prefixes + if (!href.match(/^https?:\/\//) && !href.startsWith("//")) { + // Create an absolute URL by resolving against the provided host + const absoluteUrl = new URL(href, host).href; + link.setAttribute("href", absoluteUrl); + } + } + }); + // Loop over all