使用 AJAX 并操作 window.location 时不使用弹出窗口拦截器的 window.open

2024-03-24

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

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

那么该怎么做呢?


答案很简单,并且跨浏览器工作没有任何问题。执行 AJAX 调用时(在本例中我将使用 jQuery),只需执行以下操作。假设我们有一个带有两个按钮的表单,Login with Twitter and Login 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 中的 POChttp://jsfiddle.net/CNCgG/ http://jsfiddle.net/CNCgG/

这既简单又有效:)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 AJAX 并操作 window.location 时不使用弹出窗口拦截器的 window.open 的相关文章