fix: prevent popup blocker from blocking async window.open (#29391)

This commit is contained in:
yyh
2025-12-10 12:46:01 +08:00
committed by GitHub
parent c033030d8c
commit f722fdfa6d
4 changed files with 115 additions and 25 deletions

View 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 }
}