美文网首页
如何判断页面是通过链接打开还是通过后退按钮返回打开的?

如何判断页面是通过链接打开还是通过后退按钮返回打开的?

作者: 10676 | 来源:发表于2021-05-13 11:34 被阅读0次

    解决办法

    利用浏览器的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.
      7.2 The PerformanceNavigation interface
      官方链接地址

    我的故事

    前端前辈大哥用的是template.js模板引擎进行页面的局部渲染,url通过php进行构建的,导致我没有办法改变url,点击浏览器回退的时候没有办法记录之前页数,SO~~~


    唉!好心酸 唉,好无奈

    相关文章

      网友评论

          本文标题:如何判断页面是通过链接打开还是通过后退按钮返回打开的?

          本文链接:https://www.haomeiwen.com/subject/zfbtjltx.html