最近在使用微信、支付宝、百度钱包实现网页支付,对支付成功将自动关闭页面,对于支付失败,将显示错误信息。当在错误页面的时候,点击返回或者Android物理按键上一步的时候,将关闭页面。
微信公众号开发的时候,可能会出现这种需求:
微信公众号内指定某个网页在点击返回键时不回退到上一级,而是直接关闭微信浏览器窗口
解决方案:
方法一:使用微信网页开发,调用JS-SDK API,wx.closeWindow
实现步骤:
1、签名URL
//初始化微信JSAPIfunction initWxJsApi(){//签名url,http://localhost/wx/jsp/test.html?sid=fsevar url = window.document.location.href;ajaxSyncRequest(getContextPath() + "signUrl", {"url": url}, function(data){if(data.success){wx.config({ debug: false, appId: data.sign.appId, timestamp: data.sign.timestamp, nonceStr: data.sign.nonceStr, signature: data.sign.signature, jsApiList : ['closeWindow'] });wx.error(function(res) { alert("出错了:" + res.errMsg); });wx.ready(function() { wx.checkJsApi({ jsApiList : ['closeWindow'], success : function(res) { } }); //点击返回键时,直接退出微信浏览器onBackCloseWindow();});}else{showDlg("签名url失败: " + data.msg);}});}
2、wx.ready()中调用onBackCloseWindow();,函数如下:
//当点击返回键时,不返回到上一页,而是直接关闭微信浏览器function onBackCloseWindow() {pushHistory();window.addEventListener("popstate", function(e) {//关闭当前浏览器wx.closeWindow();}, false);function pushHistory() {var state = {title: "title",url: "#"};window.history.pushState(state, "title", "#");} }
补充:
pushState
history.pushState(state, title, url)
:无刷新的向浏览器历史最前方加入一条记录。
state
(any) 需要保存的数据,这个数据在触发popstate
事件时保存在event.state
上。title
(string):url
(string) 需要更改的url
地址。
ps:pushState
需要至少两个参数。
popstate
: 浏览器点击前进后退时触发的事件。event.state
可以获取当前url下设置的state
。
另外获取pushState
中设置的state
不一定要在popstate
事件中获取,直接history.state
也可以拿到。
方法二:
以下方法无需授权、签名也可以
$(function(){setTimeout('WeixinJSBridge.call("closeWindow")', 1500);});
//当点击返回键时,不返回到上一页,而是直接关闭微信浏览器function onBackCloseWindow() {pushHistory();window.addEventListener("popstate", function(e) {//关闭当前浏览器WeixinJSBridge.call("closeWindow");}, false);function pushHistory() {var state = {title: "title",url: "#"};window.history.pushState(state, "title", "#");} }
完!!!