前端在做微信支付的时候,支付成功后点击微信自带的返回键会返回到调起微信钱包的页面并因为支付参数错误而报错,因此想到了js监听微信自带返回键的方法改变返回的页面,如下方法:
if(window.history && window.history.pushState) {
$(window).on('popstate', function() {
var hashLocation = location.hash;
var hashSplit = hashLocation.split("#!/");
var hashName = hashSplit[1];
if(hashName !== '') {
var hash = window.location.hash;
if(hash === '') {
alert("你点击了返回键");
}
}
});
window.history.pushState('forward', null, './#forward');
}
但尝试后发现是行不通的,没法监听微信的返回键,多方查找后最终通过location.replace()方法解决,如下:
function jsApiCall()
{
WeixinJSBridge.invoke(
'getBrandWCPayRequest',
<?php echo $jsApiParameters; ?>,
function(res){
WeixinJSBridge.log(res.err_msg);
if (res.err_msg == "get_brand_wcpay_request:ok") {
window.location.replace("order/payment/success")
} else if (res.err_msg == "get_brand_wcpay_request:cancel") {
// 跳转到待支付订单页面
window.location.replace("order/payment/fail");
// history.go(-1);
} else if (res.err_msg == "get_brand_wcpay_request:fail") {
alert('支付失败')
// 跳转到待支付订单页面
window.location.replace("order/payment/fail");
}
}
);
}
function callpay()
{
if (typeof WeixinJSBridge == "undefined"){
if( document.addEventListener ){
document.addEventListener('WeixinJSBridgeReady', jsApiCall, false);
}else if (document.attachEvent){
document.attachEvent('WeixinJSBridgeReady', jsApiCall);
document.attachEvent('onWeixinJSBridgeReady', jsApiCall);
}
}else{
jsApiCall();
}
}
window.onload = function(){
if (typeof WeixinJSBridge == "undefined"){
if( document.addEventListener ){
document.addEventListener('WeixinJSBridgeReady', editAddress, false);
}else if (document.attachEvent){
document.attachEvent('WeixinJSBridgeReady', editAddress);
document.attachEvent('onWeixinJSBridgeReady', editAddress);
}
}else{
editAddress();
}
callpay();
};
使用replace后,浏览器记录里就不会记录当前调起钱包的页面了,因此在支付成功页面点击默认的后退键可以跳过调起页面而返回调起的上一个页面