mirror of
https://github.com/langgenius/dify.git
synced 2026-05-02 08:28:03 +08:00
50 lines
1.2 KiB
TypeScript
50 lines
1.2 KiB
TypeScript
'use client'
|
|
import { useEffect } from 'react'
|
|
|
|
export const useOAuthCallback = () => {
|
|
useEffect(() => {
|
|
if (window.opener) {
|
|
window.opener.postMessage({
|
|
type: 'oauth_callback',
|
|
}, '*')
|
|
window.close()
|
|
}
|
|
}, [])
|
|
}
|
|
|
|
export const openOAuthPopup = (url: string, callback: () => void) => {
|
|
try {
|
|
const parsedUrl = new URL(url)
|
|
|
|
if (parsedUrl.protocol !== 'http:' && parsedUrl.protocol !== 'https:') {
|
|
console.error('Invalid URL protocol, only http: and https: are allowed')
|
|
return null
|
|
}
|
|
|
|
const width = 600
|
|
const height = 600
|
|
const left = window.screenX + (window.outerWidth - width) / 2
|
|
const top = window.screenY + (window.outerHeight - height) / 2
|
|
|
|
const popup = window.open(
|
|
parsedUrl.toString(), // 使用解析和验证后的 URL
|
|
'OAuth',
|
|
`width=${width},height=${height},left=${left},top=${top},scrollbars=yes`,
|
|
)
|
|
|
|
const handleMessage = (event: MessageEvent) => {
|
|
if (event.data?.type === 'oauth_callback') {
|
|
window.removeEventListener('message', handleMessage)
|
|
callback()
|
|
}
|
|
}
|
|
|
|
window.addEventListener('message', handleMessage)
|
|
return popup
|
|
}
|
|
catch (error) {
|
|
console.error('Invalid URL:', error)
|
|
return null
|
|
}
|
|
}
|