我正在开发一个纯JavaScript的OAuth身份验证流程,我想在弹出窗口中向用户显示“授予访问权限”窗口,但它被阻塞了。
我如何防止弹出窗口创建的任何窗口。打开或打开窗户。showModalDialog从被不同的浏览器的弹出窗口拦截器阻止?
我正在开发一个纯JavaScript的OAuth身份验证流程,我想在弹出窗口中向用户显示“授予访问权限”窗口,但它被阻塞了。
我如何防止弹出窗口创建的任何窗口。打开或打开窗户。showModalDialog从被不同的浏览器的弹出窗口拦截器阻止?
当前回答
我不想让新的页面,除非回调成功返回,所以我这样做来模拟用户点击:
function submitAndRedirect {
apiCall.then(({ redirect }) => {
const a = document.createElement('a');
a.href = redirect;
a.target = '_blank';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
});
}
其他回答
基于Jason Sebring的非常有用的技巧,以及这里和那里覆盖的东西,我找到了一个完美的解决方案:
伪代码与Javascript片段:
immediately create a blank popup on user action var importantStuff = window.open('', '_blank'); (Enrich the call to window.open with whatever additional options you need.) Optional: add some "waiting" info message. Examples: a) An external HTML page: replace the above line with var importantStuff = window.open('http://example.com/waiting.html', '_blank'); b) Text: add the following line below the above one: importantStuff.document.write('Loading preview...'); fill it with content when ready (when the AJAX call is returned, for instance) importantStuff.location.href = 'https://example.com/finally.html'; Alternatively, you could close the window here if you don't need it after all (if ajax request fails, for example - thanks to @Goose for the comment): importantStuff.close();
我实际上使用这个解决方案进行邮件重定向,它适用于我所有的浏览器(windows 7, Android)。顺便说一下,_blank位有助于邮件重定向在移动设备上工作。
我的用例:在我的react应用程序中,在用户单击后端执行API调用。根据响应,打开新选项卡,并将api响应作为参数添加到新选项卡URL(在同一域中)。
在我的用例中,唯一需要注意的是,接收API响应需要1秒钟的时间。因此弹出窗口阻止显示(如果它是活跃的)时,打开URL在一个新的选项卡。
为了避免上述问题,下面是示例代码,
var new_tab=window.open()
axios.get('http://backend-api').then(response=>{
const url="http://someurl"+"?response"
new_tab.location.href=url;
}).catch(error=>{
//catch error
})
总结:创建一个空选项卡(如上面的第1行),当API调用完成时,您可以用url填充选项卡并跳过弹出窗口阻止程序。
我已经通过使用setTimeOut函数来管理这一点。
setTimeOut(function(){
window.location.replace("https://www.google.com/");
}, 1000)
✅✅✅✅✅
只需使用window。location。href = yourUrl或者target='_blank'的url
Window.open()有太多问题,如果距离用户操作超过一秒钟,很多浏览器会将其视为弹出窗口并阻止它
@here 我发现它在所有浏览器中都可以正常工作
window.open(URL) || window.location.assign(URL)