mirror of
http://112.124.100.131/huang.ze/ebiz-dify-ai.git
synced 2025-12-23 01:36:55 +08:00
改进iframe消息通道实现和更新应用标题
This commit is contained in:
@@ -9,7 +9,7 @@ import './styles/globals.css'
|
||||
import './styles/markdown.scss'
|
||||
|
||||
export const metadata = {
|
||||
title: 'Dify',
|
||||
title: 'AgentAI',
|
||||
}
|
||||
|
||||
export const viewport: Viewport = {
|
||||
|
||||
@@ -1,26 +1,60 @@
|
||||
'use client'
|
||||
|
||||
// 定义一个全局的 MessageChannel 用于 iframe 通信
|
||||
let port
|
||||
let port: MessagePort | null = null
|
||||
|
||||
export function activeMessageChannel() {
|
||||
// 只监听一次初始化消息,接收到后自动移除监听器
|
||||
// 确保代码只在客户端运行
|
||||
if (typeof window === 'undefined') return
|
||||
|
||||
// 检查是否在 iframe 中
|
||||
const isInIframe = window !== window.parent
|
||||
|
||||
if (!isInIframe) {
|
||||
console.log('不在 iframe 中,无需激活消息通道')
|
||||
return
|
||||
}
|
||||
|
||||
// console.log('在 iframe 中,准备接收消息通道')
|
||||
|
||||
// 监听来自父窗口的消息
|
||||
window.addEventListener('message', function initHandler(event) {
|
||||
console.log('尝试接收初始化消息:', event.data)
|
||||
try {
|
||||
// console.log('接收到消息:', event.data)
|
||||
|
||||
console.log('接收到初始化消息,设置端口')
|
||||
port = event.ports[0]
|
||||
// 检查消息中是否包含 MessagePort
|
||||
if (event.ports && event.ports.length > 0) {
|
||||
// console.log('接收到包含 MessagePort 的消息')
|
||||
|
||||
// 设置端口消息处理函数
|
||||
port.onmessage = (msgEvent) => {
|
||||
console.log('接收到worker消息:', msgEvent.data)
|
||||
// 保存端口
|
||||
port = event.ports[0]
|
||||
|
||||
// 设置端口消息处理函数
|
||||
port.onmessage = (/* msgEvent */) => {
|
||||
// console.log('通过 MessagePort 接收到消息:', msgEvent.data)
|
||||
}
|
||||
|
||||
// 将 port 暴露到全局对象
|
||||
// 使用 any 类型避免 TypeScript 错误
|
||||
(window as any).port = port
|
||||
|
||||
// 向父窗口发送确认消息
|
||||
window.parent.postMessage('port-received', '*')
|
||||
|
||||
// 通过端口发送就绪消息
|
||||
port.postMessage({
|
||||
type: 'ready',
|
||||
message: 'iframe 已准备好通信',
|
||||
})
|
||||
|
||||
// 初始化完成后移除这个事件监听器
|
||||
window.removeEventListener('message', initHandler)
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
console.error('处理消息时出错:', error)
|
||||
}
|
||||
})
|
||||
|
||||
Object.defineProperty(globalThis, 'port', {
|
||||
value: port,
|
||||
})
|
||||
|
||||
// 初始化完成后移除这个事件监听器
|
||||
window.removeEventListener('message', initHandler)
|
||||
}, /* {
|
||||
once: true,
|
||||
} */)
|
||||
// console.log('消息通道监听已激活,等待父窗口发送 MessagePort')
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user