我正在开发一个纯JavaScript的OAuth身份验证流程,我想在弹出窗口中向用户显示“授予访问权限”窗口,但它被阻塞了。

我如何防止弹出窗口创建的任何窗口。打开或打开窗户。showModalDialog从被不同的浏览器的弹出窗口拦截器阻止?


当前回答

摆脱这种情况最简单的方法是:

不要使用document.open()。 而是使用this.document.location.href = location;要加载的url在哪里

例:

<script>
function loadUrl(location)
{
this.document.location.href = location;
}</script>

<div onclick="loadUrl('company_page.jsp')">Abc</div>

这对我来说非常有效。 干杯

其他回答

我的用例:在我的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填充选项卡并跳过弹出窗口阻止程序。

另外瑞士先生张贴,在我的情况下窗口。Open是在一个承诺中启动的,它打开了弹出窗口拦截器,我的解决方案是: 角:

$scope.gotClick = function(){

  var myNewTab = browserService.openNewTab();
  someService.getUrl().then(
    function(res){
        browserService.updateTabLocation(res.url, myNewTab);

    }
  );
};

browserService:

this.openNewTab = function(){
     var newTabWindow = $window.open();
     return newTabWindow;
}

this.updateTabLocation = function(tabLocation, tab) {
     if(!tabLocation){
       tab.close();
     }
     tab.location.href = tabLocation;
}

这就是如何使用承诺响应而不调用弹出窗口阻止程序打开一个新选项卡。

我不想让新的页面,除非回调成功返回,所以我这样做来模拟用户点击:

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

我已经通过使用setTimeOut函数来管理这一点。

setTimeOut(function(){
  window.location.replace("https://www.google.com/");
}, 1000)

✅✅✅✅✅

The general rule is that popup blockers will engage if window.open or similar is invoked from javascript that is not invoked by direct user action. That is, you can call window.open in response to a button click without getting hit by the popup blocker, but if you put the same code in a timer event it will be blocked. Depth of call chain is also a factor - some older browsers only look at the immediate caller, newer browsers can backtrack a little to see if the caller's caller was a mouse click etc. Keep it as shallow as you can to avoid the popup blockers.