zoukankan      html  css  js  c++  java
  • sessionStorage 与 localStorage 重新认识?

      之前写过一次关于 js存储的总结,但是今天在项目中遇到一个bug让我重新在认识 sessionStorage 与 localStorage。以下的介绍都是基于同源下进行的,仔细看下面的案例:

    a.html

    <script>
        function add() {
          window.sessionStorage.setItem("test", "a页面的数据")
          // window.localStorage.setItem("test", "a页面的数据")
        }
      </script>
      <button onclick="add()">存储数据</button>
    
      <a href="b.html" target="_blank">前往b页面</a>
      <!-- <a href="b.html">前往b页面</a> -->
    

    b.html

    <a href="a.html">前往a页面</a>
      <script>
        function remove() {
          window.sessionStorage.removeItem("test");
          // window.localStorage.removeItem("test");
        }
      </script>
      <button onclick="remove()">清除</button>
    

      

    《1》先看 sessionStorage 情况

        a.页面跳转打开新窗口情况下

              

       b.页面跳转在当前窗口内

      

      通过上面的案例看出:

        通过带target="_blank"的a标签、window.open、location.href等方式打开新窗口时,会把旧窗口(或标签)的sessionStorage数据带过去,但从此之后,新窗口(或标签)的sessionStorage的增删改和旧窗口已经没有关系了。如果只是在当前窗口内跳转新页面(或者刷新),数据之间还是存在关系的。

    《2》先看 localStorage 情况

      a.页面跳转打开新窗口情况下

      

       b.页面跳转在当前窗口内

      

      通过上面的案例看出:

        不管是通过带target="_blank"的a标签、window.open、location.href等方式打开新窗口,还只是在当前窗口内跳转新页面(或者刷新),localStorage存储数据之间还是存在关系的 

          

      从上面的案例 所以在处理sessionStorage时,只要打开新窗口就要特别注意了,新旧窗口数据不会互相同步。

     

  • 相关阅读:
    Mysql Got a packet bigger than 'max_allowed_packet' bytes
    Git之IDEA集成Git更新项目Update Type选项解释
    IDEA获取GIT仓库时更新类型update type的选择
    git merge和git rebase的区别
    git merge和git merge --no-ff的区别
    Git中fetch和pull命令的区别
    git官网下载太慢解决方法
    IDEA执行Thread.activeCount() = 2的问题
    k8s 常见错误汇总
    Axure9破解
  • 原文地址:https://www.cnblogs.com/changxue/p/11176430.html
Copyright © 2011-2022 走看看