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

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


当前回答

作为一个好的实践,我认为这是一个好主意,测试一个弹出窗口是否被阻止,并采取行动,以防万一。你需要了解那个窗口。Open有一个返回值,如果操作失败,该值可能为空。例如,在以下代码中:

function pop(url,w,h) {
    n=window.open(url,'_blank','toolbar=0,location=0,directories=0,status=1,menubar=0,titlebar=0,scrollbars=1,resizable=1,width='+w+',height='+h);
    if(n==null) {
        return true;
    }
    return false;
}

如果弹出窗口被阻塞,窗口。Open将返回null。所以函数会返回false。

例如,想象一下直接从任何链接调用这个函数 target="_blank":如果弹出窗口被成功打开,返回 False将阻塞链接动作,否则如果弹出窗口被阻塞, 返回true将允许默认的行为(打开新的_blank 窗口)然后继续。

<a href="http://whatever.com" target="_blank" onclick='return pop("http://whatever.com",300,200);' >

这样你就会有一个弹出窗口,如果它工作,和一个_blank窗口 不是。

如果弹出框没有打开,你可以:

像例子中那样打开一个空白窗口,然后继续 打开一个假的弹出窗口(页面内的iframe) 通知用户(“请允许本网站弹出窗口”) 打开一个空白窗口,然后通知用户 等。

其他回答

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.

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

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

另外瑞士先生张贴,在我的情况下窗口。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;
}

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

我尝试了多种解决方案,但他的解决方案是唯一一个在所有浏览器中都有效的解决方案

let newTab = window.open(); newtable .location.href = url;

从谷歌的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