最近在写h5 的时候要求去掉页面的前进和后退的横栏,记录一下自己的解决方案。
1. 首先说明一下h5的流程
前端调起h5 授权 > 用code 从服务器换取token > 记录下token,之后的每次请求带上token
2. 发生问题的原因
每次h5授权的时候,微信会重定向,这时候我们的页面就会带上这个前进和后退的横栏。
3. 怎么解决
我的想法是如果重定向不发生在前端页面而是在后台会不会就可以了?
在我们进入真正的h5 页面之前加一个过渡页面来授权。
也就是说我们的项目入口是test/index.php 而实际上的h5 代码是在index.html 里。
- 目录结构:
- 下面看一下代码:
index.php
<?php
if (!$_GET['code']){
$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=appid&redirect_uri=http://***/test/index.php&response_type=code&scope=snsapi_base&state=1#wechat_redirect';
die(header('location:'.$url));
}else{
die(header('location:http://***/test/index.html?code='.$_GET['code']));
}
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
这是我们的h5 页面
</body>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script src="//cdn.bootcss.com/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
<script>
function getQueryString(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
var r = window.location.search.substr(1).match(reg);
if(r != null) return decodeURI(r[2]);
return null;
}
</script>
</html>
也就是从index.php 进入后会带着code 被重定向到index.html。