fix(HTML预览): 修复链接点击影响父窗口问题

- 注入 <base target="_blank"> 标签
- 智能检测现有 head/html 标签位置注入
- 确保预览中的链接在新标签页打开
- 避免链接影响主应用页面
This commit is contained in:
gaoziman 2025-12-21 02:47:27 +08:00
parent b3d5a47072
commit 2e5120dc72

View File

@ -1,6 +1,6 @@
'use client';
import { useState, useCallback, useEffect, useRef } from 'react';
import { useState, useCallback, useEffect, useRef, useMemo } from 'react';
import {
X,
Monitor,
@ -83,6 +83,29 @@ export function HtmlPreviewModal({
// 获取当前设备配置
const currentDevice = deviceConfigs.find((d) => d.type === device) || deviceConfigs[0];
// 处理 HTML 代码,注入 <base target="_blank"> 防止链接影响父窗口
const processedHtmlCode = useMemo(() => {
const baseTag = '<base target="_blank">';
// 检查是否已经有 <base> 标签
if (/<base\s/i.test(htmlCode)) {
return htmlCode;
}
// 尝试在 <head> 标签后注入
if (/<head[^>]*>/i.test(htmlCode)) {
return htmlCode.replace(/<head[^>]*>/i, `$&\n ${baseTag}`);
}
// 尝试在 <html> 标签后注入
if (/<html[^>]*>/i.test(htmlCode)) {
return htmlCode.replace(/<html[^>]*>/i, `$&\n <head>\n ${baseTag}\n </head>`);
}
// 如果都没有,在最前面添加
return `<head>${baseTag}</head>\n${htmlCode}`;
}, [htmlCode]);
// ESC 关闭 / F11 全屏切换
useEffect(() => {
if (!isOpen) return;
@ -348,7 +371,7 @@ export function HtmlPreviewModal({
{/* iframe 预览 */}
<iframe
key={iframeKey}
srcDoc={htmlCode}
srcDoc={processedHtmlCode}
sandbox="allow-scripts allow-same-origin"
className="w-full bg-white"
style={{