0

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. The issue that I am having is the cookie is not saving when the user input reaches a certain length. It seems to be working fine with small strings.

Here is the 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');
    }

Any ideas what could be going on? Thanks!

cfly24
  • 1,882
  • 3
  • 22
  • 56

1 Answers1

2

The max size of a cookie is 4093 bytes. Perhaps the long string is just eclipsing that limit. You could consider localStorage or sessionStorage instead

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

Community
  • 1
  • 1
Mike
  • 1,266
  • 1
  • 11
  • 17