Last updated on
异步请求后进行 window.open 被拦截
问题如题,去找了一些参考,为什么要被拦截
https://javascript.info/popup-windows
In the past, evil sites abused popups a lot. A bad page could open tons of popup windows with ads. So now most browsers try to block popups and protect the user.
Most browsers block popups if they are called outside of user-triggered event handlers like onclick.
For example:
// popup blocked
window.open('https://javascript.info');
// popup allowed
button.onclick = () => {
window.open('https://javascript.info');
};
This way users are somewhat protected from unwanted popups, but the functionality is not disabled totally.
出于安全和用户友好考虑,限制了 window.open 的调用
如何解决呢?
const mockApi = () => new Promise((resolve) => {
setTimeout(() => {
resolve('hello')
}, 4000)
})
function Demo1() {
useEffect(() => {
mockApi().then((res) => {
// window.open("https://baidu.com")
})
}, [])
return (
<div onClick={async () => {
const newWindow = window.open() as any
await mockApi()
if (!newWindow?.location) {
return
}
newWindow.location.href = 'https://baidu.com'
}}>Demo1</div>
)
}