js判断页面是否是通过浏览器后退按钮返回打开的

举报
薛定喵君 发表于 2021/04/07 12:19:03 2021/04/07
【摘要】 背景最近使用uni-app开发项目时遇到了一个bug,需求是需要在两个平台之间切换,A平台登录后要选择身份,选完后带着token进入另外一个平台B的个人空间,点击个人空间顶部的个人信息区域又可以切换到A平台的身份选择。这样子就产生了一个问题,点击身份的时候会生成新的token,但是页面是允许返回的所以url地址栏中的历史token还在,所以就会基于这个token触发请求导致接口报了Toke...

背景

最近使用uni-app开发项目时遇到了一个bug,需求是需要在两个平台之间切换,A平台登录后要选择身份,选完后带着token进入另外一个平台B的个人空间,点击个人空间顶部的个人信息区域又可以切换到A平台的身份选择。
这样子就产生了一个问题,点击身份的时候会生成新的token,但是页面是允许返回的所以url地址栏中的历史token还在,所以就会基于这个token触发请求导致接口报了Token验证失败的错误,一番搜索之后终于找到了解决办法。

解决方法

利用浏览器的window.performance.navigation.type属性

window.performance.navigation.type

window.performance是W3C性能小组引入的新的API,目前IE9以上的浏览器都支持。
我们可以在官方说明中找到PerformanceNavigation接口的详细介绍:


[Exposed=Window]
interface PerformanceNavigation {
  const unsigned short TYPE_NAVIGATE = 0;
  const unsigned short TYPE_RELOAD = 1;
  const unsigned short TYPE_BACK_FORWARD = 2;
  const unsigned short TYPE_RESERVED = 255;
  readonly attribute unsigned short type;
  readonly attribute unsigned short redirectCount;
  [Default] object toJSON();
};

type 属性返回值为0,1,2。分别对应三个枚举值:

  • 0 : TYPE_NAVIGATE
    • Navigation where the history handling behavior is set to “default” or “replace”.(用户通过常规导航方式访问页面,比如点一个链接,或者一般的get方式)
  • 1 : TYPE_RELOAD
    • Navigation where the history handling behavior is set to “reload”.(用户通过刷新,包括JS调用刷新接口等方式访问页面)
  • 2 : TYPE_BACK_FORWARD
    • Navigation where the history handling behavior is set to “entry update”.(用户通过后退按钮访问本页面)
  • 255 : TYPE_RESERVED
    • Any navigation types not defined by values above.(上面的值未定义的任何导航类型)
  • type
    • This attribute must return the type of the last non-redirect navigation in the current browsing context. It must have one of the following navigation type values.

    NOTE
    Client-side redirects, such as those using the Refresh pragma directive, are not considered HTTP redirects by this spec. In those cases, the type attribute should return appropriate value, such as TYPE_RELOAD if reloading the current page, or TYPE_NAVIGATE if navigating to a new URL.(客户端重定向,例如使用Refresh pragma伪指令的客户端重定向,在本规范中不视为HTTP重定向。在这些情况下,该type 属性应返回适当的值,例如 TYPE_RELOAD重新加载当前页面或 TYPE_NAVIGATE导航到新URL)

  • redirectCount
    • This attribute must return the number of redirects since the last non-redirect navigation under the current browsing context. If there is no redirect or there is any redirect that is not from the same origin as the destination document, this attribute must return zero.
  • toJSON()
    • Runs [WEBIDL]'s default toJSON operation.

所以我们只要判断type属性为2时就可以知道页面是通过返回按钮打开的了,然后开头的问题就可以据此加判断来解决token异常了。

适用场景

如果在做基于vue等框架开发的前端项目、uni-app来开发h5相关项目时都可以参考上述方法去实现功能

参考资料

【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@huaweicloud.com
  • 点赞
  • 收藏
  • 关注作者

评论(0

0/1000
抱歉,系统识别当前为高风险访问,暂不支持该操作

全部回复

上滑加载中

设置昵称

在此一键设置昵称,即可参与社区互动!

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

*长度不超过10个汉字或20个英文字符,设置后3个月内不可修改。

举报
请填写举报理由
0/200