Title: JavaScript, Fourth Edition
1JavaScript, Fourth Edition
- Chapter 9
- Managing State Information and Security
2Objectives
- Learn about state information
- Save state information with hidden form fields,
query strings, and cookies - Learn about security issues
JavaScript, Fourth Edition
2
2
3Understanding State Information
- State information
- Information about individual visits to a Web site
- HTTP was originally designed to be stateless
- Browsers stored no persistent data about site
visits - Reasons for maintaining state information
- Customize individual Web pages
- Temporarily store information for a user
- i.e. a multipart form
- Allow a user to create bookmarks
- Provide shopping carts
4Understanding State Information
- Reasons for maintaining state information
- Store user IDs and passwords
- Use counters
- Keep Game Top Scores
- Example
- Frame-based Color Printer Product Registration
Web page - Customer Information
- Product Information
- The forms are designed so that data entered on
both is submitted to a web server simultaneously.
JavaScript, Fourth Edition
4
5Understanding State Information (continued)
JavaScript, Fourth Edition
5
6Understanding State Information (continued)
JavaScript, Fourth Edition
6
7Saving State Information with Hidden Form Fields
- Hidden form field
- Special type of form element
- Not displayed by the Web browser
- Allows you to hide information from users
- Created with the ltinputgt element
- Temporarily store data that needs to be sent to a
server along with the rest of a form - But that a user does not need to see
- Syntax
- ltinput type"hidden"gt
JavaScript, Fourth Edition
7
8Saving State Information with Hidden Form Fields
(continued)
JavaScript, Fourth Edition
8
9Saving State Information with Hidden Form Fields
(continued)
- Example
- Add hidden form fields to the Color Printer
Product Registration program - Add code to the Customer Information document
that copies its form field values to the hidden
form fields in the top frame of the Color Printer
Product Registration frameset - Add code to the Product Information document that
copies its form field values to the hidden form
fields in the top frame of the Color Printer
Product Registration frameset
JavaScript, Fourth Edition
9
10Saving State Information with Query Strings
- Query string
- Set of namevalue pairs appended to a target URL
- Consists of a single text string containing one
or more pieces of information - You can use a query string to pass information
from one Web page to another
11Passing Data with a Query String
- To pass data from one web page to another using a
query string - Add a question mark (?) immediately after a URL
- Followed by the query string (in namevalue
pairs) for the information you want to preserve - You separate individual namevalue pairs within
the query string using ampersands () - The passed query string is then assigned to the
search property - Of the target Web page Location object
- location.search
JavaScript, Fourth Edition
11
12Passing Data with a Query String
- Example
- Similar to passing arguments to functions
- lta hrefhttp//www.URL.com/TargetPage.html?firstN
ameDonlastNameGosselinoccupationwritergt
Link Text lt/agt - The passed query string is assigned to the search
property of the target web page location object. - Search property sets/returns the URL from the
question mark (?). - Assume that the current URL is
- http//w3schools.com/js/tryit.asp?filenametry_loc
_search - ltscript type"text/javascript"gt
- document.write(location.search)
- lt/script
- Outputs ?filenametry_loc_search
JavaScript, Fourth Edition
12
13Parsing Data from a Query String
- Modify the Color Printer Product Registration
page to pass registration information as query
strings (p448)
JavaScript, Fourth Edition
13
14Parsing Data from a Query String
- Modify the Color Printer Product Registration
page to pass registration information as query
strings - Remove the question mark
- Using the substring() method combined with the
length property - Convert the individual pieces of information into
array elements - Using the split() method
- Example
- Write your own parsing script that extracts and
displays the data in the query string
JavaScript, Fourth Edition
14
15Parsing Data from a Query String (continued)
JavaScript, Fourth Edition
15
16Saving State Information with Cookies
- Query strings and hidden form fields maintain
state information only temporarily - Cookies
- Small pieces of information about a user that are
stored by a Web server in text files - On the users computer
- Each time the Web client visits a Web server
- Saved cookies are sent from the client to the
server - Temporary cookies
- Remain available only for current browser session
JavaScript, Fourth Edition
16
17Saving State Information with Cookies (continued)
- Persistent cookies
- Remain available beyond current browser session
- And are stored in a text file on a client
computer - Limitations on the use of cookies
- Server or domain can store a maximum of 20
cookies - Total cookies per browser cannot exceed 300
- Largest cookie size is 4 kilobytes
JavaScript, Fourth Edition
17
18Creating Cookies
- Use the cookie property of the Document object
- To create cookies in namevalue pairs
- The name attribute
- Only required parameter
- Specifies the cookies namevalue pair
- document.cookie firstname Don
- document.cookie lastname Smith
- Cookies created with only the name attribute are
temporary cookies - Cookies cannot include semicolons or special
characters - Web browser separates each name / value pair with
a semicolon and space - firstnameDon lastnameSmith
- You can use special characters in your cookies if
you use encoding (converting text to hexadecimal)
JavaScript, Fourth Edition
18
19Creating Cookies (continued)
- The name attribute (continued)
- Encoding involves converting special characters
in a text string - To their corresponding hexadecimal ASCII value
- encodeURIComponent() function
- Used for encoding the individual parts of a URI
- Converts special characters in the individual
parts of a URI to their corresponding hexadecimal
ASCII value - tipa standard tip is 15 encoded reads
- tipA20standard20tip20is201525
- decodeURIComponent() function
- Counterpart of encodeURIComponent() function
JavaScript, Fourth Edition
19
20Creating Cookies (continued)
- The name attribute (continued)
- You should manually encode and decode cookies
- Example
- Modify the Customer Information form so its
fields are saved in temporary cookies instead of
in query strings - The expires attribute
- Determines how long a cookie can remain on a
client system before it is deleted - document.cookie namevalue expiresdate
- Cookies created without this attribute are
available for only the current browser session - Be sure not to encode this attribute
- Must be text in UTC format Mon Dec 27 141518
PST 2008
JavaScript, Fourth Edition
20
21Creating Cookies (continued)
- The expires attribute (continued)
- You can manually type a string in UTC format
- Or you can create the string with the Date object
- Use the toUTCString() method to convert the Date
object to a string - var expiresDate new Date()
- expiresDate.setFullYear(expiresDate.getFullYear()
1) //Fri Apr 3 141035 EDT 2009 - document.cookie firstname
encodeURIComponent(Don) expires
expiresDate.toUTCstring() - Unused persistent cookies can sometimes interfere
with the execution of a JavaScript cookie program - Good idea to delete browser cookies periodically
- Example
- Add to ProductInfo.html a persistent cookie named
registered that is assigned a value of true when
the user clicks the Submit button
JavaScript, Fourth Edition
21
22Creating Cookies (continued)
- The path attribute
- Determines the availability of a cookie to other
Web pages on a server - By default, a cookie is available to all Web
pages in the same directory - To make a cookie available to all directories on
a server, use a slash - document.cookie firstname
encodeURIComponent(Don path/) - Cookies from other programs that are stored in
the same directory - Can cause your JavaScript cookie program to run
erratically
JavaScript, Fourth Edition
22
23Creating Cookies (continued)
- The domain attribute
- Used for sharing cookies across multiple servers
in the same domain - You cannot share cookies outside of a domain
- The secure attribute
- Indicates that a cookie can only be transmitted
across a secure Internet connection - Using HTTPS or another security protocol
- document.cookie firstname
encodeURIComponent(Don securetrue)
JavaScript, Fourth Edition
23
24Reading Cookies
- Parsing a cookie
- Decode it using decodeURIComponent() function
- Use the methods of the String object to extract
individual namevalue pairs - Example
- Modify the code in ProductInfo.html so it does
not refer to the query string - Add code to the Register.html document that reads
and prints the contents of the cookies from the
CustomerInfo.html document
JavaScript, Fourth Edition
24
25Reading Cookies (continued)
- Example
- Modify CustomerInfo.html so it reads the
persistent registered cookie to determine whether
the user has already submitted the product
registration
JavaScript, Fourth Edition
25
26Understanding Security Issues
- Discuss security issues that relate to Web
browsers and JavaScript
JavaScript, Fourth Edition
26
27Secure Coding with JavaScript
- Security threats
- Viruses, worms, and data theft by hackers
- Consider both Web server security issues and
secure coding issues - Web server security technologies
- Firewalls
- Secure Socket Layer (SSL)
- Encrypts data and sends over a secure connection
- JavaScript programs are downloaded and execute
locally
JavaScript, Fourth Edition
27
28Secure Coding with JavaScript (continued)
- Secure coding or defensive coding
- Writing code to minimize any intentional or
accidental security issues - First line of defense is to validate all user
input - Exception handling to handle script errors or
user input errors - All code is insecure unless proven otherwise
- No magic formula for writing secure code
JavaScript, Fourth Edition
28
29JavaScript Security Concerns
- Security areas of most concern
- Protection of a Web page and JavaScript program
against malicious tampering - Privacy of individual client information
- Protection of the local file system of the client
or Web site from theft or tampering - Another security concern
- Privacy of individual client information in the
Web browser window - E-mail addresses should be hidden from e-mail
harvesters - Bookmarks
- History
- An important JavaScript security feature
- Its lack of certain types of functionality
- No access to commands, network or file-system I/O
JavaScript, Fourth Edition
29
30JavaScript Security Concerns (continued)
- Missing functionalities
- File manipulation
- Create a network connection
- Cannot run system commands or execute programs on
a client
JavaScript, Fourth Edition
30
31The Same Origin Policy
- Same origin policy
- Restricts how JavaScript code in one window or
frame accesses a Web page - In another window or frame on a client computer
- To view and modify the elements in other windows
and frames - They must have the same protocol and exist on the
same Web server - Same origin policy applies not only to the domain
name - But also to server on which a document is located
JavaScript, Fourth Edition
31
32The Same Origin Policy (continued)
- Policy prevents malicious scripts from modifying
the content of other windows and frames - And prevents the theft of private browser
information and information displayed on secure
Web pages - Policy also protects the integrity of the design
of your Web page - Example
- Create a frame set in which one frame uses
JavaScript code to try to change the status bar
text of another frame
JavaScript, Fourth Edition
32
33The Same Origin Policy (continued)
- domain property of the Document object
- Changes the origin of a document to its root
domain name - Allows documents from different origins in the
same domain to access each others elements and
properties
JavaScript, Fourth Edition
33
34Summary
- Information about individual visits to a Web site
is called state information - HTTP was originally designed to be stateless
- You can hide information from users in a hidden
form field - Most common tools for maintaining state
information are hidden form fields, query
strings, and cookies - A query string is a set of namevalue pairs
appended to a target URL
35Summary (continued)
- Cookies are small pieces of information about a
user that are stored by a Web server - Cookies can be temporary or persistent
- The cookie property is created with a required
name attribute - You can use special characters in your cookies if
you use encoding - The built-in encodeURIComponent() function
encodes the individual parts of a URI
36Summary (continued)
- When you read a cookie or other text string
encoded, you must first decode it with the
decodeURIComponent() function - Cookies are one continuous string that must be
parsed - Secure coding, or defensive coding, refers to
writing of code to minimize any intentional or
accidental security issues
JavaScript, Fourth Edition
36
37Summary (continued)
- The same origin policy restricts how JavaScript
code in one window or frame accesses a Web page
in another window or frame on a client computer. - The domain property of the Document object
changes the origin of a document to its root
domain name using the statement document.domain
domain