mirror of
https://github.com/langgenius/dify.git
synced 2025-12-19 22:28:46 +00:00
fix: prevent popup blocker from blocking async window.open (#29391)
This commit is contained in:
72
web/hooks/use-async-window-open.ts
Normal file
72
web/hooks/use-async-window-open.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import { useCallback } from 'react'
|
||||
import Toast from '@/app/components/base/toast'
|
||||
|
||||
export type AsyncWindowOpenOptions = {
|
||||
successMessage?: string
|
||||
errorMessage?: string
|
||||
windowFeatures?: string
|
||||
onError?: (error: any) => void
|
||||
onSuccess?: (url: string) => void
|
||||
}
|
||||
|
||||
export const useAsyncWindowOpen = () => {
|
||||
const openAsync = useCallback(async (
|
||||
fetchUrl: () => Promise<string>,
|
||||
options: AsyncWindowOpenOptions = {},
|
||||
) => {
|
||||
const {
|
||||
successMessage,
|
||||
errorMessage = 'Failed to open page',
|
||||
windowFeatures = 'noopener,noreferrer',
|
||||
onError,
|
||||
onSuccess,
|
||||
} = options
|
||||
|
||||
const newWindow = window.open('', '_blank', windowFeatures)
|
||||
|
||||
if (!newWindow) {
|
||||
const error = new Error('Popup blocked by browser')
|
||||
onError?.(error)
|
||||
Toast.notify({
|
||||
type: 'error',
|
||||
message: 'Popup blocked. Please allow popups for this site.',
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
const url = await fetchUrl()
|
||||
|
||||
if (url) {
|
||||
newWindow.location.href = url
|
||||
onSuccess?.(url)
|
||||
|
||||
if (successMessage) {
|
||||
Toast.notify({
|
||||
type: 'success',
|
||||
message: successMessage,
|
||||
})
|
||||
}
|
||||
}
|
||||
else {
|
||||
newWindow.close()
|
||||
const error = new Error('Invalid URL received')
|
||||
onError?.(error)
|
||||
Toast.notify({
|
||||
type: 'error',
|
||||
message: errorMessage,
|
||||
})
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
newWindow.close()
|
||||
onError?.(error)
|
||||
Toast.notify({
|
||||
type: 'error',
|
||||
message: errorMessage,
|
||||
})
|
||||
}
|
||||
}, [])
|
||||
|
||||
return { openAsync }
|
||||
}
|
||||
Reference in New Issue
Block a user