JavaScript is a script that runs on the client, so it is generally not possible to set a session because the session is run on the server side.
Cookies are run on the client, so you can use JS to set cookies.
JS Set Cookie method Rollup:
First type:
<script>
//Set cookie
function Setcookie (CNAME, cvalue, exdays) {
var d = new Date ();
D.settime (D.gettime () + (exdays*24*60*60*1000));
var expires = "expires=" +d.toutcstring ();
Document.cookie = cname + "=" + Cvalue + ";" + Expires;
}
Gets
the cookie 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)!=-1) return c.substring (Name.length, c.length);
Return "";
}
Clears the cookie
function ClearCookie (name) {
Setcookie (name, "",-1);
}
function Checkcookie () {
var user = GetCookie ("username");
if (User!= "") {
alert ("Welcome again" + user);
} else {
user = prompt ("Please enter your name:", "");
if (User!= "" && user!= null) {
Setcookie ("username", user, 365);
}} Checkcookie ();
</script>
The second type:
<script>
//js How to operate cookies!
Write Cookies
function Setcookie (c_name, value, expiredays) {
var exdate=new Date ();
Exdate.setdate (exdate.getdate () + expiredays);
Document.cookie=c_name+ "=" + Escape (value) + ((expiredays==null)? ":"; expires= "+exdate.togmtstring ());
}
Read Cookies
function GetCookie (name)
{
var arr,reg=new RegExp ("(^|)" +name+ "= ([^;] *)(;|$)");
if (Arr=document.cookie.match (reg)) return
(arr[2]);
else return
null;
}
Delete Cookies
function Delcookie (name)
{
var exp = new Date ();
Exp.settime (Exp.gettime ()-1);
var cval=getcookie (name);
if (cval!=null)
document.cookie= name + "=" +cval+ "; expires=" +exp.togmtstring ();
}
Use
The example Setcookie (' username ', ' Darren ', ')
alert (GetCookie ("username"));
</script>
A third example
Attention:
The Chrome browser cannot get cookies locally. Must be available on the server. If it is local, you can place it under the WWW directory of the locality.
Google Chrome only supports cookies for online web sites, and cookies for local HTML are prohibited. So the following code if you write in a local HTML file, the pop-up dialog box content is empty.
Document.cookie = "Test=cooo";
alert (Document.cookie);
If this page is the content of the online Web site, the cookie content will be displayed normally test=cooo and so on.
The above mentioned is the entire content of this article, I hope you can enjoy.