您的位置:首页 > 移动开发 > 微信开发

微信公众号网页开发监控手机后退并关闭页面到主页

2017-09-16 15:24 281 查看
这个部分需要用到三个东西:

history.pushState

window.onpopstate

微信内置浏览器JS:
WeixinJSBridge.call('closeWindow');


你可以在最后一个(需要点击返回退出浏览器的)页面载入的时候借助
history.pushState
保存下两个状态:
history.pushState({page : 'state1'},'state','#state1');
history.pushState({page : 'state2'},'state','#state2');


然后监听返回按钮的点击事件(事实上就是出发了浏览器的历史记录变动事件),当监听到用户点击返回按钮时执行类似下面的函数,调用微信内置JS函数
WeixinJSBridge.call('closeWindow');
关闭浏览器,即可完成用户点击返回按钮退出微信浏览器的操作。:

window.onpopstate = function(event) {
if (event.state.page === 'state1') {
WeixinJSBridge.call('closeWindow');
}
}

java ee开发 页面如下

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<!DOCTYPE HTML>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<base href="<%=basePath%>">
<html lang="zn-cn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0">
<title>出错了</title>
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<link rel="stylesheet"href="css/service.css">
<script type="text/javascript" src="js/exit.js"></script>
</head>
<script type="text/javascript">
history.pushState({page : 'state1'},'state','#state1'); history.pushState({page : 'state2'},'state','#state2');
window.onpopstate = function(event) { if (event.state.page === 'state1') { WeixinJSBridge.call('closeWindow'); } }
</script>
<body>
<div class='nonetwork'>
<img src='img/nonetwork.png'>
<h3>抱歉!当前会话已过期</h3>
<h3>请重新打开页面</h3>
</div>
</body>

</html>


点击手机的后退按钮,则关闭该页面到公众号主页
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: