gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 01:23:10 25 4
gpt4 key购买 nike

在处理来自服务器(例如 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com