项目背景
近期我司上线了一个大型项目,包括后台管理系统、互联网pc端(面向大众)和移动端(面向大众)
需求
项目上线之后,需求想要实现一个功能:
(1).客户在移动设备上输入pc端的网址(https://www.pc.com)系统要自动跳转到移动端网址(https://www.mobile.com)上进行后续操作;
(2).客户在移动端的网址上(htts://www.mobile.com)有一个向pc端网址跳转的链接,点击之后,跳转到pc端(https://www.pc.com)进行后续操作。
我
心情比较复杂,这是什么无理要求,想要操作哪个系统,就登陆哪个系统,不就可以了吗,干嘛要这样难为我们。实现不了...
然而我知道,所有的牢骚和埋怨都没有什么用,客户需求第一,产品质量大如天。整理思路干吧...
我
思路:
1.通过navigator.userAgent判断是否移动设备
2.对移动端网址向pc端的网址的跳转增加辨认标识
移动端的代码实现
//移动端的代码(?from=mobile进行标识)
<address>
如查询详细参数,请访问 :
<a
href="https://www.pc.com?from=mobile"
>www.pc.com</a>
</address>
pc端的代码实现
// 代码如下
// pc端的处理代码
// 判断是否移动端
_isMobile() {
const reg = /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i;
const flag = navigator.userAgent.match(reg);
return flag;
}
// 对路由跳转的判断(对移动端的跳转路由增加标识判断)
if ("from=mobile" == window.location.href.split("?")[1]) {
window.location.replace("https://www.pc.com");
}else if (this._isMobile()) {
window.location.replace("https://www.mobile.com");
}
我
此时貌似松了口气,自测发现
1.现在可以实现在移动设备上输入www.pc.com自动跳转到了www.mobile.com上
2.但是无法实现从移动端网址向pc端网址的跳转
这可怎么办?。。。
我
继续寻找思路:
1.通过navigator.userAgent判断是否移动设备
2.对移动端网址向pc端的网址的跳转增加辨认标识
3.在pc端对增加的标识进行存储
思路分析
// 本地存储
方案一 使用localStorage进行存储
方案二 使用sessionStorage进行存储
方案三 使用cookie进行存储
选型分析
1. 本功能不能长期存储,否则永远不能再跳转到移动系统
2. 只针对本次跳转有效,页面关闭限制消失
结论
1. 如果使用localStorage进行存储,还需要在某个时刻清除存储
2. 使用sessionStorage和cookie只需要存储,不需要有清除动作
3. 使用cookie存储会将这些信息发送到服务端,这些信息对服务端来说并没有什么作用
4. 最后我选择使用sessionStorage
修改pc端代码
if ("from=mobile" == window.location.href.split("?")[1]) {
// 对标识符进行存储
sessionStorage.setItem("mobile", window.location.href.split("?")[1] || "");
window.location.replace("https://www.pc.com");
// 判断标识符
} else if ("from=mobile" == sessionStorage.getItem("mobile")) {
window.location.replace("https://www.pc.com");
} else if (this._isMobile()) {
window.location.replace("https://www.mobile.com");
}
我
这次总该可以了吧,然而测试发现从移动端跳转到pc端之后,页面会一直刷新,根本进入不到首页。
这是怎么了。。。
现象分析
从测试的现象来看,这次是不会再跳转回到移动系统了,但是页面一直再刷新,形成了死循环。这是由于遇到了 else if('from=mobile' === sessionStorage.getItem("mobile")){
window.location.replace("https://www.pc.com")
}这层判断,所以会一直刷新系统。所以对呀这层判断直接放行就行了。。。
最终实现
if ("from=mobile" == window.location.href.split("?")[1]) {
// 对标识符进行存储
sessionStorage.setItem("mobile", window.location.href.split("?")[1] || "");
window.location.replace("https://www.pc.com");
// 判断标识符
} else if ("from=mobile" == sessionStorage.getItem("mobile")) {
// 啥也不用做,只要进入不到下面的判断就行了
// window.location.replace("https://www.pc.com");
} else if (this._isMobile()) {
window.location.replace("https://www.mobile.com");
}