非同期処理を挟み、window.open()
を実行すると、ポップアップブロックに引っかかる。
(Reactで実装)
const handleClick = async () => { try { const url = await getURL() // 非同期処理 open.window(url, '_blank') } catch (e) { console.error(e) } }
とにかく別タブで開きたい。
先に空のwindowを開き、後でurlを入れる。
errorなどでcloseなどを行う。
(手元のChrome,Safari,Edge,Firefoxでは機能した)
const handleClick = async () => { try { let openWindow = window.open('', '_blank') const url = await getURL() // 非同期処理 openWindow.localtion.href = openWindow } catch (e) { openWindow.close() console.error(e) } }
諦めて、処理を分ける。
const [targetURL, setTargetURL] = useState('') const handleGenerateURL = async () => { try { const url = await getURL() // 非同期処理 setTargetURL(url) } catch (e) { console.error(e) } } const handleClick = async () => { targetURL && window.open(targetURL, '_blank') }
useEffect()
を使用して、{ href && <a href={href} />}
のようにセットしておく