Search code examples
javascripthtmlcookies

Why Doesn't document.cookie work In A Web File?


I Can't Make A Cookie In An Html File...

document.cookie = "Lang:Ar";

When It's Time To Preview:

In Inspect Section > Console :

document.cookie
''

So I Tried To Turn The Cookie Into A Function :

function SetCookie(Key,Val) {
    document.cookie = Key + "=" + Val;
}

But It Didn't Success...

1.Creating The Cookie :

SetCookie("Lang","Ar");
"Lang", "Ar"

2.Previewing It :

document.cookie
''

The Same Thing 😭

But It Worked Only On LiveServer In VScode.


Solution

  • If you are working entirely on the front-end, you can use WebStorage.

    With WebStorage, you have two options:


    Example:

    You can use localStorage as follows:

    localStorage.setItem('Lang', 'Ar');
    
    localStorage.getItem('Lang'); // Ar