当用户输入达到一定大小时,Javascript cookie不会保存

时间:2015-07-14 16:07:13

标签: javascript jquery html cookies

我试图在卸载页面时在javascript cookie中保存textarea中的用户输入,然后在用户返回时将其读回textarea。我遇到的问题是当用户输入达到一定长度时cookie不会保存。用小字符串似乎工作正常。

这是html:

<html>
<head>
<title>Cookie Test</title>
<link rel="stylesheet" type="text/css" href="css/site.css">
</head>
<body class="full" onload="GetCookies()" onunload="WriteCookies()">
    <div class="fullscreen-overlay" id="fullscreen_overlay">
  <div class="fullscreen-container js-fullscreen-container">
<div class="textarea-wrap">
  <textarea name="fullscreen-contents" id="fullscreen-contents"></textarea>
</div>
 </div>
</div>
</body>
</html>

使用Javascript:

function WriteCookies() {
        var d = new Date();
        var n = document.getElementById('fullscreen-contents').value;
        d.setDate(d.getDate() + 1);
        document.cookie = "mainCookie = " + n + "; expires = " + d.toGMTString() + "";
    }

    function getCookie(cname) {
        var name = cname + "=";
        var ca = document.cookie.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 "";
    }

    function GetCookies() {
        document.getElementById('fullscreen-contents').value = getCookie('mainCookie');
    }

任何想法可能会发生什么?谢谢!

1 个答案:

答案 0 :(得分:2)

Cookie的最大大小为4093 bytes。也许长串只是超过了这个限制。您可以考虑使用localStorage or sessionStorage

var text = document.getElementById('fullscreen-contents');

function saveText() {
  localStorage.savedText = text.value;
  console.log("saved");
}

function getText() {
  if (localStorage.savedText) {
    text.value = localStorage.savedText;
    console.log("loaded");
  }
}

已编辑:此处为fiddle