简体   繁体   English

当用户输入达到一定大小时,JavaScript cookie无法保存

[英]Javascript cookie not saving when user input reaches a certain size

I am trying to Save user input from a textarea in a javascript cookie on the unload of a page and then read it back into a textarea when the user returns. 我正在尝试在页面卸载时将来自textarea的用户输入保存在javascript cookie中,然后在用户返回时将其读回textarea。 The issue that I am having is the cookie is not saving when the user input reaches a certain length. 我遇到的问题是,当用户输入达到一定长度时,cookie无法保存。 It seems to be working fine with small strings. 小字符串似乎很好用。

Here is the html: 这是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: 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');
    }

Any ideas what could be going on? 有什么想法怎么回事? Thanks! 谢谢!

The max size of a cookie is 4093 bytes . Cookie的最大大小为4093字节 Perhaps the long string is just eclipsing that limit. 也许长字符串恰好超过了该限制。 You could consider localStorage or sessionStorage instead 您可以考虑使用localStorage或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");
  }
}

Edited: Here is a fiddle 编辑:这是一个小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM