0

I have multiple pages,

login.html
 -a.html
 -b.html
 .
 .
 -z.html

when user login,I want all this page can get the user information,like user_id and user_name. but without session,how can i do this only in javascript?

Yago Azedias
  • 4,480
  • 3
  • 17
  • 31
kennyname
  • 11
  • 1

2 Answers2

1

There are many ways to solve your problem:

Browser's cookies

You can use the browser cookie to get data of a specific domain, like you can see on this W3 school page. One attempt is that you are able to read cookies using your server side

To set a cookie's browser you can do something like this:

var user_name = "John Doe"
var user_id = 1235456
document.cookie = "user_name=" + user_name;
document.cookie = "user_id=" + user_id;

To get the data you can use this function, created on kirlich's answer:

function getCookie(name) {
    var value = "; " + document.cookie;
    var parts = value.split("; " + name + "=");
    if (parts.length == 2) return parts.pop().split(";").shift();
}

getCookie("user_name"); // => John Doe

Local Storage

Local storage has a difference, its can only be read by the client side. Turns your data safe against Cross-site request forgery:

localStorage.setItem("user_name", "John Doe");
localStorage.getItem("user_name"); // => "John Doe"

Session Storage

The sessionStorage object is equal to the localStorage object, except that it stores the data for only one session. The data is deleted when the user closes the specific browser tab.

sessionStorage.username = "John Doe";
console.log(sessionStorage.username); // => "John Doe"
Yago Azedias
  • 4,480
  • 3
  • 17
  • 31
0

Use localStorage

var userId = document.getElementById('userId').value;
localStorage.setItem('User Id', userId);

Then on each html page get the User Id with:

var someVariable = localStorage.getItem('User Id');
Ryan Walker
  • 715
  • 2
  • 10
  • 23