我正在开发一个纯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位有助于邮件重定向在移动设备上工作。

从谷歌的oauth JavaScript API:

http://code.google.com/p/google-api-javascript-client/wiki/Authentication

请看上面写着:

设置认证

OAuth 2.0的客户端实现使用一个弹出窗口来提示用户登录并批准应用程序。第一次调用gapi.auth.authorize可以触发弹出窗口拦截器,因为它间接地打开了弹出窗口。为了防止弹出窗口阻止程序在认证调用时触发,在客户端加载时调用gapi.auth.init(回调)。当库准备进行身份验证调用时,将执行提供的回调。

我猜这与上面的真实答案有关,它解释了如果有立即的反应,它不会触发弹出警报。“gapi.auth。Init使API立即发生。

实际应用

我在npm上使用节点护照和每个提供商的各种护照包创建了一个开源身份验证微服务。我使用了一个标准的重定向方法到第三方,给它一个重定向URL回来。这是程序化的,所以我可以有不同的地方重定向回如果登录/注册和特定的页面。

github.com/sebringj/athu

passportjs.org

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

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

✅✅✅✅✅

@here 我发现它在所有浏览器中都可以正常工作

window.open(URL) || window.location.assign(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;
}

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