Javascript 防止弹出窗口被阻止

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4956359/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 14:57:09  来源:igfitidea点击:

Prevent pop-ups from being blocked

javascriptfacebookpopup

提问by Seema

I am using a Facebook login method in my code on page load, but when I execute this code, the pop-up blocker closes the Facebook permission window.

我在页面加载的代码中使用 Facebook 登录方法,但是当我执行此代码时,弹出窗口阻止程序关闭 Facebook 权限窗口。

How can I open this window with Javascriptwithout needing to make an exception in the pop-up blocker?

如何在Javascript不需要在弹出窗口阻止程序中设置例外的情况下打开此窗口?

Below is my code:

下面是我的代码:

FB.login(function(response)
{
    if(response.session!=null)
    {
        window.location.href='http://example.com';
    }
},
{ perms: 'email,user_birthday,publish_stream' });

回答by Rahul

You can do something like -

你可以做这样的事情 -

var uri = encodeURI('http://example.com');
FB.getLoginStatus(function(response) {
      if (response.status === 'connected') {
                window.location.href=uri;
      } else {
         window.location = encodeURI("https://www.facebook.com/dialog/oauth?client_id=YOUR_APP_ID&redirect_uri="+uri+"&response_type=token");
      }

This will just redirect directly instead of opening a pop-up

这将直接重定向而不是打开弹出窗口

回答by dubilla

This is specifically denied in the documentation:

文档中明确否认了这一点:

"You should only call this on a user event as it opens a popup. Most browsers block popups, unless they were initiated from a user event, such as a click on a button or a link."

“您应该只在打开弹出窗口时在用户事件上调用它。大多数浏览器都会阻止弹出窗口,除非它们是从用户事件启动的,例如单击按钮或链接。”

It's also simply poor UX.

这也只是糟糕的用户体验。

回答by Anthony Grist

There'd be no point in popup blockers existing if you could just code around them. You'll either need to find a method that doesn't use a popup or require some user interaction with the browser to open the popup.

如果您可以围绕它们进行编码,那么现有的弹出窗口阻止程序就毫无意义。您要么需要找到一种不使用弹出窗口的方法,要么需要与浏览器进行一些用户交互才能打开弹出窗口。

回答by Enmanuel Hernandez

Yeah you need to call it with a user event, but strictly the onclickevent, not any other:

是的,您需要使用用户事件来调用它,但严格来说是onclick事件,而不是其他任何事件:

<a href="#" onclick="fbLogin()"> Login</a> <!-- works -->

<a href="#" onmousedown="fbLogin()"> Login</a> <!-- doesnt work -->

<a href="#" onmouseup="fbLogin()"> Login</a> <!-- doesnt work -->

回答by Arnab

If you try to open a popup automatically then there is a high possibility that popup blockers will become activated, as far as I know, it has to be based on some User action, for example click of a button. Try to execute this code on click of a button, it should work.

如果您尝试自动打开弹出窗口,则很有可能会激活弹出窗口阻止程序,据我所知,它必须基于某些用户操作,例如单击按钮。尝试在单击按钮时执行此代码,它应该可以工作。