Fix image relative url error

修复相对链接图片无法显示问题
This commit is contained in:
2025-06-02 11:54:12 +08:00
parent c252ceafb2
commit daad7aeecd
2 changed files with 69 additions and 24 deletions
+39 -7
View File
@@ -25,8 +25,15 @@ const removeAttributes = (el: HTMLElement) => {
});
}
interface FormatHTMLOptions {
formatter?: (doc: Document) => void;
baseURL?: string;
}
// 格式化 HTML 内容
export const formatHTML = (html: string, extraFormatter?: (doc: Document) => void) => {
export const formatHTML = (html: string, options: FormatHTMLOptions = {}) => {
const { formatter, baseURL } = options;
// 删除空格
html = html.replaceAll(" ", "");
@@ -64,11 +71,30 @@ export const formatHTML = (html: string, extraFormatter?: (doc: Document) => voi
// 优化 img 标签,仅保留有效内容
const imgEl = nextDocument.querySelectorAll("img") as NodeListOf<HTMLImageElement>;
imgEl.forEach((el) => {
const nextImgEl = document.createElement("img");
nextImgEl.src = el.src;
nextImgEl.alt = el.alt;
const tempImg = document.createElement("img");
el.parentNode.replaceChild(nextImgEl, el);
// 创建一个临时的 a 元素来解析相对路径
const tempLink = document.createElement("a");
tempLink.href = el.src;
// 如果提供了 baseURL 且图片链接是相对路径,则使用 baseURL 构建完整链接
if (baseURL && !tempLink.href.startsWith('http')) {
tempImg.src = new URL(el.src, baseURL).href;
} else {
tempImg.src = tempLink.href;
}
tempImg.alt = el.alt;
// 复制 width 和 height 属性
if (el.width) {
tempImg.width = el.width;
}
if (el.height) {
tempImg.height = el.height;
}
el.parentNode.replaceChild(tempImg, el);
});
// 删除 figure 标签
@@ -88,6 +114,12 @@ export const formatHTML = (html: string, extraFormatter?: (doc: Document) => voi
el.remove();
});
// 删除 script 标签
const scriptEl = nextDocument.querySelectorAll("script");
scriptEl.forEach((el) => {
el.remove();
});
// 提取 pre 下面的内容
const preEl = nextDocument.querySelectorAll("pre");
preEl.forEach((el) => {
@@ -105,8 +137,8 @@ export const formatHTML = (html: string, extraFormatter?: (doc: Document) => voi
}
});
if (extraFormatter) {
extraFormatter(nextDocument);
if (formatter) {
formatter(nextDocument);
}
return nextDocument.documentElement.innerHTML;