当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 在微信、支付宝、百度钱包实现点击返回按钮关闭当前页面和窗口的方法

在微信、支付宝、百度钱包实现点击返回按钮关闭当前页面和窗口的方法

2019年07月29日  | 移动技术网IT编程  | 我要评论

最近在使用微信、支付宝、百度钱包实现网页支付,对支付成功将自动关闭页面,对于支付失败,将显示错误信息。当在错误页面的时候,点击返回或者android物理按键上一步的时候,将关闭页面。

在微信、支付宝、百度钱包中,他们对页面关闭进行了封装,传统的window.close()是无效的,必须要使用它们的js代码才能关闭。

下面是三种移动app的关闭方式:

weixinjsbridge.call('closewindow');//微信 
alipayjsbridge.call('closewebview'); //支付宝 
blightapp.closewindow();//百度钱包

通过浏览器的头判断是那种浏览器:

var ua = navigator.useragent.tolowercase(); 
f(ua.match(/micromessenger/i)=="micromessenger") { 
alert("微信客户端"); 
} else if(ua.indexof("alipay")!=-1){ 
alert("支付宝客户端"); 
}else if(ua.indexof("baidu")!=-1){ 
alert("百度客户端"); 
}

对返回、上一页、后退进行监听,并对history中放入当前页地址:

$(function(){ 
pushhistory(); 
window.addeventlistener("popstate", function(e) { 
}, false); 
function pushhistory() { 
var state = { 
title: "title", 
url: "#" 
}; 
window.history.pushstate(state, "title", "#"); 
} 
});

整个实现完整代码:

$(function(){ 
pushhistory(); 
window.addeventlistener("popstate", function(e) { 
pushhistory(); 
var ua = navigator.useragent.tolowercase(); 
if(ua.match(/micromessenger/i)=="micromessenger") { 
weixinjsbridge.call('closewindow'); 
} else if(ua.indexof("alipay")!=-1){ 
alipayjsbridge.call('closewebview'); 
}else if(ua.indexof("baidu")!=-1){ 
blightapp.closewindow(); 
} 
else{ 
window.close(); 
} 
}, false); 
function pushhistory() { 
var state = { 
title: "title", 
url: "#" 
}; 
window.history.pushstate(state, "title", "#"); 
} 
});

以上所述是小编给大家介绍的在微信、支付宝、百度钱包实现点击返回按钮关闭当前页面和窗口的方法,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网