欢迎加入QQ群一起探讨交流:581902292

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时,只要打开新窗口就要特别注意了,新旧窗口数据不会互相同步。

 

 

posted @ 2019-07-12 15:42  £AP︶ㄣOL◢◤LO  阅读(219)  评论(0编辑  收藏  举报