0

I tried to save a cookies via JavaScript

var parser = new UAParser();
var result = parser.getResult();

console.log(result.ua);
document.cookie = "cookiename=" + JSON.stringify(result.ua);
<script src=" https://cdn.jsdelivr.net/npm/ua-parser-js@0.7.28/src/ua-parser.min.js "></script>

And only a part of the cookie is saved.I tried to encode and JSON.stringify but not a difference

debug info

mplungjan
  • 169,008
  • 28
  • 173
  • 236
  • `;` is a special character in `document.cookie` and `JSON.stringify` won't escape it for you. Use a function designed to manipulating `document.cookie` instead of rolling your own. – Quentin Sep 14 '21 at 15:06
  • try `encodeURIComponent(result.ua)` instead of JSON.stringify – mplungjan Sep 14 '21 at 15:08
  • @mplungjan — If you're going to use JSON.stringify at all (and there doesn't seem any point since I think `result.ua` is a string) it should be inside the `encodeURIComponent` not outside it. – Quentin Sep 14 '21 at 15:09
  • @mplungjan — If the value is a string then converting it to JSON is pointless. If the value is an object or an array then calling `encodeURIComponent` before `JSON.stringify` will implicitly convert it to a string using `.toString()` which will break it. – Quentin Sep 14 '21 at 15:23
  • JSON.stringify does more than convert something to a string. It manipulates the quotes and other entities - but yeah, Overkill - as you can see I edited my comment – mplungjan Sep 14 '21 at 15:28

0 Answers0