File tree 3 files changed +57
-0
lines changed
JavaScript/Advance/BOM/9.cookie-II
3 files changed +57
-0
lines changed Original file line number Diff line number Diff line change
1
+ <!DOCTYPE html>
2
+ < html lang ="en ">
3
+
4
+ < head >
5
+ < meta charset ="UTF-8 ">
6
+ < meta http-equiv ="X-UA-Compatible " content ="IE=edge ">
7
+ < meta name ="viewport " content ="width=device-width, initial-scale=1.0 ">
8
+ < title > cookie-part-II-JS</ title >
9
+ < link rel ="shortcut icon " href ="images/js-logo.png " type ="image/x-icon ">
10
+ </ head >
11
+
12
+ < body >
13
+
14
+ </ body >
15
+ < h1 > Cookie in JS</ h1 >
16
+ < p id ="textOne "> </ p >
17
+ < button onclick ="checkCookie() "> click</ button >
18
+ < script src ="script.js "> </ script >
19
+
20
+ </ html >
Original file line number Diff line number Diff line change
1
+ let textOne = document . getElementById ( 'textOne' ) ;
2
+
3
+ function setCookie ( cname , cvalue , exdays ) {
4
+ const d = new Date ( ) ;
5
+ d . setTime ( d . getTime ( ) + ( exdays * 24 * 60 * 60 * 1000 ) ) ;
6
+ let expires = "expires=" + d . toUTCString ( ) ;
7
+ document . cookie = cname + "=" + cvalue + ";" + expires + ";path=/" ;
8
+ textOne . innerHTML = document . cookie ;
9
+ }
10
+
11
+ function getCookie ( cname ) {
12
+ let name = cname + "=" ;
13
+ let decodedCookie = decodeURIComponent ( document . cookie ) ;
14
+ let ca = decodedCookie . split ( ';' ) ;
15
+ for ( let i = 0 ; i < ca . length ; i ++ ) {
16
+ let c = ca [ i ] ;
17
+ while ( c . charAt ( 0 ) == ' ' ) {
18
+ c = c . substring ( 1 ) ;
19
+ }
20
+ if ( c . indexOf ( name ) == 0 ) {
21
+ return c . substring ( name . length , c . length ) ;
22
+ }
23
+ }
24
+ return "" ;
25
+ }
26
+
27
+ function checkCookie ( ) {
28
+ let user = getCookie ( "username" ) ;
29
+ if ( user != "" ) {
30
+ alert ( "Welcome again " + user ) ;
31
+ } else {
32
+ user = prompt ( "Please enter your name:" , "" ) ;
33
+ if ( user != "" && user != null ) {
34
+ setCookie ( "username" , user , 30 ) ;
35
+ }
36
+ }
37
+ }
You can’t perform that action at this time.
0 commit comments