Browse Source

Add iframe load handling in Project.vue to update document title and favicon dynamically. This enhancement improves the user experience by ensuring the displayed content reflects the iframe's metadata.

deploy
dash 10 months ago
parent
commit
5ffab4ade2
  1. 45
      frontend/src/views/Project.vue

45
frontend/src/views/Project.vue

@ -2,9 +2,11 @@
<div class="project-page">
<iframe
v-if="previewUrl"
ref="previewIframe"
:src="previewUrl"
class="preview-iframe"
sandbox="allow-scripts allow-same-origin allow-forms"
@load="handleIframeLoad"
></iframe>
<div v-if="!isInIframe" class="control-buttons">
<button @click="goHome" class="control-btn back-btn" title="BACK HOME">
@ -110,6 +112,7 @@ const drawerVisible = ref(false);
const documentVisible = ref(false);
const currentDocument = ref<Document | null>(null);
const previewUrl = ref('');
const previewIframe = ref<HTMLIFrameElement | null>(null);
const isInIframe = computed(() => {
return window.self !== window.top;
@ -175,6 +178,48 @@ const formatDate = (dateString: string) => {
return date.toLocaleString('zh-CN');
};
const handleIframeLoad = () => {
if (!previewIframe.value) return;
try {
const iframeDoc = previewIframe.value.contentDocument || previewIframe.value.contentWindow?.document;
if (!iframeDoc) return;
// 更新 title
const iframeTitle = iframeDoc.title;
if (iframeTitle) {
document.title = iframeTitle;
}
// 更新 favicon
const faviconLink = iframeDoc.querySelector('link[rel="icon"], link[rel="shortcut icon"]') as HTMLLinkElement;
if (faviconLink) {
const faviconHref = faviconLink.href;
// 如果是相对路径,需要转换为绝对路径
let absoluteFaviconUrl = faviconHref;
if (faviconHref.startsWith('/') || !faviconHref.startsWith('http')) {
const iframeBaseUrl = new URL(previewUrl.value, window.location.origin);
absoluteFaviconUrl = new URL(faviconHref, iframeBaseUrl).href;
}
// 移除旧的 favicon
const existingFavicon = document.querySelector('link[rel="icon"], link[rel="shortcut icon"]');
if (existingFavicon) {
existingFavicon.remove();
}
// 添加新的 favicon
const link = document.createElement('link');
link.rel = 'icon';
link.href = absoluteFaviconUrl;
document.head.appendChild(link);
}
} catch (error) {
// 如果由于跨域问题无法访问 iframe 内容,静默失败
console.warn('无法访问 iframe 内容:', error);
}
};
onMounted(() => {
loadProject();
});

Loading…
Cancel
Save