ajax - window.open 没有使用 AJAX 和操作 window.location 的弹出窗口阻止程序

标签 ajax popup twitter-oauth facebook-oauth window.open

在处理来自服务器(例如 Twitter 和 Facebook)的 OAuth 时,您很可能会将用户重定向到一个请求应用程序许可的 URL。通常,单击链接后,您通过 AJAX 将请求发送到服务器,然后返回授权 URL。

但是当您尝试使用 window.open 时收到答复后,您的浏览器会阻止弹出窗口,使其无用。当然,您可以将用户重定向到新的 URL,但这会破坏用户体验,而且很烦人。您不能使用 IFRAMES,但不允许使用它们(因为您看不到位置栏)。

那么怎么做呢?

最佳答案

答案很简单,可以跨浏览器运行,没有任何问题。在执行 AJAX 调用时(在本例中我将使用 jQuery),只需执行以下操作。假设我们有一个带有两个按钮的表单,Login with TwitterLogin with Facebook .

<button type="submit" class="login" value="facebook" name="type">Login with Facebook</button>
<button type="submit" class="login" value="twitter" name="type">Login with Twitter</button>

然后是魔法发生的 Javascript 代码

$(function () {
    var
        $login = $('.login'),
        authWindow;

    $login.on('click', function (e) {
        e.preventDefault();
        /* We pre-open the popup in the submit, since it was generated from a "click" event, so no popup block happens */
        authWindow = window.open('about:blank', '', 'left=20,top=20,width=400,height=300,toolbar=0,resizable=1');
        /* do the AJAX call requesting for the authorize URL */

        $.ajax({
            url: '/echo/json/',
            type: "POST",
            data: {"json": JSON.stringify({"url": 'http://' + e.target.value + '.com'})}
            /*Since it's a jsfiddle, the echo is only for demo purposes */
        })
        .done(function (data) {
            /* This is where the magic happens, we simply redirec the popup to the new authorize URL that we received from the server */
            authWindow.location.replace(data.url);
        })
        .always(function () {
            /* You can poll if the window got closed here, and so a refresh on the main page, or another AJAX call for example */
        });
    });
});

这是 JSFiddle 中的 POC http://jsfiddle.net/CNCgG/

这很简单有效:)

关于ajax - window.open 没有使用 AJAX 和操作 window.location 的弹出窗口阻止程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16361813/

相关文章:

javascript - 基于对象属性的数组和变量名的数组

jquery - 使用 Ajax/jQuery 动态加载内容时无法加载 Facebook 评论

java - 打开弹出窗口后程序卡住了

c# - 使用 c# (telerik) 在 wpf 中自定义弹出窗口设计

java - 使用 Twitter4j 时的凭据设置问题

jquery - 基于另一个 Textbox MVC 4 填充文本框

javascript - 如何在 Firebug 中过滤来自控制台的 AJAX 请求?

javascript - 如何让 Mailchimp 弹出窗口在 Chrome 中工作

oauth - 为什么不鼓励前端的 OAuth key ?

python - 尝试在 Google Colab 上将 Twitter API Bearer Token 与 Tweepy 一起使用时出现此错误消息是什么意思