nishimura.clubnishimura.club

window.open時のポップアップブロックの回避

作成日
2022-07-25
更新日
2022-10-21

非同期処理を挟み、window.open()を実行すると、ポップアップブロックに引っかかる。

(Reactで実装)

const handleClick = async () => { try { const url = await getURL() // 非同期処理 open.window(url, '_blank') } catch (e) { console.error(e) } }

とにかく別タブで開きたい。

回避策1

先に空の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) } }

回避策2

諦めて、処理を分ける。

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') }

回避策3

useEffect()を使用して、{ href && <a href={href} />}のようにセットしておく

Related

Tags

JavaScript

Share