AJAX 请求后使用 JS 打开新标签页被阻止的解决方法

需求:发起一个 AJAX 请求,根据请求结果来打开一个新页面。

问题:AJAX 请求后,使用 window.open() 方法来打开新页面会被浏览器阻止。

解决方法:在 AJAX 请求之前,就使用 const newWindow = window.open('about:blank'); 来打开一个空白页,AJAX 请求后拿到结果,再使用 newWindow.location = 'xxx'; 来让新页面跳转到需要的地址,

例:

// 在线支付
@action onlinePayment = async() => {
if (!this.selectedPrice) {
message.info('请选择时长');
return;
}
this.payWindow = window.open('about:blank'); // 打开一个新页面
try {
let order;
// 余额支付失败转在线支付
if (this.order.orderNo && this.order.selectedPrice === this.selectedPrice) {
order = await banlaceOnlinePay(this.order.orderNo); // ajax 请求
} else {
// 直接在线支付
order = await postOnlinePay({ goods: { goodsId: this.selectedPrice, goodsNum: 1 } }); // ajax 请求
}
this.changePayResult('paying');
if (order) {
this.payWindow.location = `${getPaymentRoot()}/#/payPage/${order.payId}`; // 修改新页面的 url
this.t = setInterval(async () => {
const status = await getOrderStatus(order.orderNo);
if (status) {
this.changePaid();
this.changeShowPayResult(false);
this.order.orderNo = null;
this.order.selectedPrice = null;
}
}, 2000);
} else {
message.error('支付出现问题');
this.payWindow.close(); // 如果 ajax 出问题,则关闭新窗口
}
} catch (e) {
message.error('支付出现问题');
this.payWindow.close();
}
};

原文地址:https://www.cnblogs.com/3body/p/8616940.html