问题描述:
当使用新窗口弹出页面时,浏览器有时会默认拦截弹出,并不友好。
比如使用第三方支付宝api做支付的时候如果浏览器拦截支付弹窗,可能会导致用户不去付款。
解决方案:
方案一:浏览器拦截的机制就是认为是非用户触发的,所以会去拦截,那么我们的思路就是让他变成用户触发的,去避免浏览器进行拦截。
1、在组件加载时就去请求支付宝三方接口拿到返回的form表单数据
mounted(){
let _params = {
orderId:this.order.orderId,
amount:this.order.totalPrice,
serviceName:this.pkl.serviceChn[this.order.serviceId]
}
paymentAlipayApi(_params).then(res => {
if(res.status === 200){
this.alipayData = res.data
}
})
}
2、然后当点击立即支付的时候,就触发form的submit方法,规避浏览器拦截机制。
//确认付款
submitPay(){
if(this.paymentMethod === 0){//微信付款
this.wxData = {
orderId:this.order.orderId,
amount:this.order.totalPrice,
serviceName:this.pkl.serviceChn[this.order.serviceId]
}
this.wxShow = true
}else if(this.paymentMethod === 1){//支付宝付款
this.paymentAlipay()
}
},
//支付宝付款
paymentAlipay(){
document.querySelector('form[name="punchout_form"]').submit()
},
此种方案的缺点是就算用户选择微信付款,也还是去请求的支付宝的三方接口,似乎并不是最好的解决方式。
那么看第二种:
方案二:我们点击的时候先打开一个空白的新窗口,这种浏览器也会认为是用户点击行为而不会拦截。网上很多例子是直接给新窗口的location.href设置为新url,但是在我们这种需要表单form提交的情况下不行。那么我的思路就是获取新窗口,然后给空白的新窗口innerHTML设置为支付宝返回的表单内容,然后在空白新窗口自身打开新页面,这样也可以解决此问题。因为支付宝三方接口返回的form表单默认就是从自身页面打开的,所以该方法可以规避方案一的问题。
//支付宝付款
paymentAlipay () {
let params = {
orderId: this.orderInfo.orderId,
amount: this.orderInfo.totalPrice,
serviceName: '2018嘉年华' + this.ticket.name
}
const newWin = window.open();
paymentAlipayApi(params).then(res => {
if (res.status === 200) {
newWin.document.body.innerHTML = res.data
this.$nextTick(()=>{
newWin.document.querySelector('form[name="punchout_form"]').submit()
})
}
})
},