【问题标题】:sessionStorage - only do a behavior on initial page loadsessionStorage - 仅在初始页面加载时执行行为
【发布时间】:2018-10-28 03:11:49
【问题描述】:

我不明白 sessionStorage 是如何工作的。我希望仅在初始页面加载时发生事件。

我正在(尝试)通过检查会话是否是新的来做到这一点。思路如下:

$(function() {
  sessionStorage.setItem('isNewSession', 'true');
  if (sessionStorage.getItem("isNewSession")) {
    // do stuff on the first page load
  } else {
    // don't do it after
  }
});

所以当页面第一次加载时,看起来sessionStorage 被设置为true。之后,在用户访问页面期间,我只想发生一次的事情总是发生,因为我可以看到sessionStorage总是true

如果我将其设置为 false,如果 sessionStorage 返回 true,那么显然我想要发生的事情就不会发生。

我调查了session cookie,但这在整个用户访问期间仍然存在,而不仅仅是第一次加载。

我该如何处理?如何让事件仅在初始页面加载时触发,而在剩余用户访问期间

上下文:“事件”是导航栏中的动画。

【问题讨论】:

  • 当动画结束时 sessionStorage.setItem('isNewSession', 'false'); ?也许我不明白这个问题。
  • @Emeeus 否,因为它被设置为 false,并且动画无法运行...
  • “我希望仅在初始页面加载时发生事件” 我假设每个用户只发生一次,对吗?因为如果不是,则没有必要使用 sessionStorage ,因为 $(whatever).ready() 完成了任务。

标签: javascript jquery session


【解决方案1】:

使用 JavaScript cookie 就可以解决问题:

以下是https://stackoverflow.com/a/8733385/2969615 的略微修改版本,已针对您的目的进行了改编:

if(getCookie("hasPageBeenOpened")) {
    console.log("welcome back");
} else {
    console.log("first time eh?");

    // Build the expiration date string:
    var expiration_date = new Date();
    expiration_date.setFullYear(expiration_date.getFullYear() + 1);
    // Build the set-cookie string:
    var cookie_string = "hasPageBeenOpened=true; path=/; expires=" + expiration_date.toUTCString();
    // Create or update the cookie:
    document.cookie = cookie_string;
}

还有读取 cookie 的脚本,我从 https://www.w3schools.com/js/js_cookies.asp 获取的

function getCookie(cname) {
    var name = cname + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');
    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

【讨论】:

    【解决方案2】:

    首先sessionStorage 不适合这种任务,因为一旦用户关闭标签,它就会丢失。您应该为此使用localStorage

    From mdn web docs

    sessionStorage 属性允许您访问当前源的会话存储对象。 sessionStorage 类似于 Window.localStorage;唯一的区别是虽然存储在 localStorage 中的数据没有设置过期时间,但 存储在 sessionStorage 中的数据会在页面会话结束时被清除。只要浏览器处于打开状态,页面会话就会持续存在,并且在页面重新加载和恢复后仍然存在。

    其次,您在检查之前设置 isNewSession。虽然你应该只设置它,如果你知道它没有设置。

    所以你更正的代码应该是这样的:

    $(function() {
        // Determine if is the first time on this page
        if ( ! localStorage.getItem("beenHereBefore")) {
            localStorage.setItem('beenHereBefore', 'true');
        }
    });
    

    Fiddle

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-05-27
      • 2012-01-22
      • 2020-12-28
      • 1970-01-01
      • 2013-03-31
      • 1970-01-01
      • 1970-01-01
      • 2014-01-19
      相关资源
      最近更新 更多