0

I'm trying to add the data from localStorage to the cookie.

Here is the code:

let cookie_name = "points_trigger";
let cookie_data = localStorage.getItem('content');
document.cookie = `${cookie_name}=${cookie_data[0].outerHTML}`;

The data from localStorage is an HTML code.

This code creates a cookie but the content is undefined. And also, I don't have any errors in the console.

upss1988
  • 173
  • 3
  • 14
  • Possibly related: https://stackoverflow.com/questions/1458724/how-do-i-set-unset-a-cookie-with-jquery – Twisty Oct 14 '20 at 17:40
  • Please also provide an example of `cookie_data`. `let cookie_data = localStorage.getItem('content'); console.log(cookie_data);` – Twisty Oct 14 '20 at 17:43

2 Answers2

0

localStorage can only store strings.

So cookie_data will be a string …

(maybe "[object HTMLDivElement]" if you're trying to store an HTML element in there)

… which means that cookie_data[0] will be the first character of that string …

("[")

… and outerHTML will be undefined because strings don't have outerHTML properties.

You need to serialise the data you are storing in localStorage to a string, and then parse it on the way out.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
-1

Consider the following.

document.cookie = "points_trigger=" + localStorage.getItem('content');

This assumes that localStorage.getItem('content') contains all the neccesary details for the cookie. For example, if it contained "John Smith", the resulting code would do something like:

document.cookie = "points_trigger=John Smith";

See More: https://www.w3schools.com/js/js_cookies.asp

Twisty
  • 30,304
  • 2
  • 26
  • 45