fix(HTML预览): 修复链接点击影响父窗口问题
- 注入 <base target="_blank"> 标签 - 智能检测现有 head/html 标签位置注入 - 确保预览中的链接在新标签页打开 - 避免链接影响主应用页面
This commit is contained in:
parent
b3d5a47072
commit
2e5120dc72
@ -1,6 +1,6 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useState, useCallback, useEffect, useRef } from 'react';
|
import { useState, useCallback, useEffect, useRef, useMemo } from 'react';
|
||||||
import {
|
import {
|
||||||
X,
|
X,
|
||||||
Monitor,
|
Monitor,
|
||||||
@ -83,6 +83,29 @@ export function HtmlPreviewModal({
|
|||||||
// 获取当前设备配置
|
// 获取当前设备配置
|
||||||
const currentDevice = deviceConfigs.find((d) => d.type === device) || deviceConfigs[0];
|
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 全屏切换
|
// ESC 关闭 / F11 全屏切换
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isOpen) return;
|
if (!isOpen) return;
|
||||||
@ -348,7 +371,7 @@ export function HtmlPreviewModal({
|
|||||||
{/* iframe 预览 */}
|
{/* iframe 预览 */}
|
||||||
<iframe
|
<iframe
|
||||||
key={iframeKey}
|
key={iframeKey}
|
||||||
srcDoc={htmlCode}
|
srcDoc={processedHtmlCode}
|
||||||
sandbox="allow-scripts allow-same-origin"
|
sandbox="allow-scripts allow-same-origin"
|
||||||
className="w-full bg-white"
|
className="w-full bg-white"
|
||||||
style={{
|
style={{
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user