aspose file tools*
The moose likes HTML, CSS and JavaScript and the fly likes Global Variable Vs Cookie Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "Global Variable Vs Cookie " Watch "Global Variable Vs Cookie " New topic
Author

Global Variable Vs Cookie

Alec Lee
Ranch Hand

Joined: Jan 28, 2004
Posts: 569
I came across a javascript example which stores the state of an expandable menu (expanded vs collapsed) in cookie instead of using global variable:http://javascript.internet.com/navigation/click-to-expand-menu.html

This makes me confused . Isn't cookie mainly used for resending information to the SERVER (like jsessionid/login name of previous session). Is there any valid reason to use cookie as a global variable when no server side communication is involved?
Eric Pascarello
author
Rancher

Joined: Nov 08, 2001
Posts: 15376
    
    6
Last time I checked, JavaScript does not have a global variable that spans page refreshes.

Eric
Valentin Crettaz
Gold Digger
Sheriff

Joined: Aug 26, 2001
Posts: 7610
Alec, global variables are only valid within the same page scope. As Eric pointed out, if you either refresh the page or navigate to another one, the value of your global variables are lost, because the JavaScript context is re-inited. If you want to be able to access certain values across all of your pages, client-side cookies are one solution.


SCJP 5, SCJD, SCBCD, SCWCD, SCDJWS, IBM XML
[Blog] [Blogroll] [My Reviews] My Linked In
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 61434
    
  67

And, if you are using a server-side system such as Servlets/JSP, you can store such values in a server-side session which is more secure than cookies.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
greg buela
Ranch Hand

Joined: Sep 04, 2007
Posts: 71
Hi Bear,
How insecure are cookies? Do you mean somebody can intercept cookie data? Menu state isn't sensible information, but... session id is! And I guess the safest way to maintain session state is through a session id cookie, at least with a modern browser. Am I correct? What are the real risks?


SCJP 1.5
Eric Pascarello
author
Rancher

Joined: Nov 08, 2001
Posts: 15376
    
    6
How unsecure are cookies?
type this into the browser address bar
javascript:alert(document.cookie);

Eric
greg buela
Ranch Hand

Joined: Sep 04, 2007
Posts: 71
All right, but what are the implications of that? Aren't we protected from cross domain access to cookies? Is insecurity limited to physical access to the computer holding the cookies?
Eric Pascarello
author
Rancher

Joined: Nov 08, 2001
Posts: 15376
    
    6
Yes unless you have a XSS hole in your site or if the person using your site wants to screw with you.

Eric
 
 
subject: Global Variable Vs Cookie