Chapter 4 Cookie
Chapter 4 Cookie
Basic of Cookies
• When a web server has sent a web page to a browser, the connection is shut down, and the server forgets everything about the user.
• Cookies were invented to solve the problem "how to remember information about the user":
• When a user visits a web page, his/her name can be stored in a cookie.
• Next time the user visits the page, the cookie "remembers" his/her name.
• Cookies are saved in name-value pairs like: username = AAA Eg: username = John Doe
• When a browser requests a web page from a server, cookies belonging to the page are added to the request.
• This way the server gets the necessary data to "remember" information about users.
Contents of Cookie
Creating a cookie
- JavaScript can create, read, and delete cookies with the document.cookie property.
Eg : document.cookie = "username=John Doe";
- You can also add an expiry date (in UTC time). By default, the cookie is deleted when the browser is closed.
Eg : document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC";
- With a path parameter, you can tell the browser what path the cookie belongs to. By default, the cookie belongs to the current page.
Eg : document.cookie = "username=John Doe; expires=Thu, 18 Dec 2013 12:00:00 UTC; path=/";<html>
<head>
<script type = "text/javascript">
function WriteCookie()
{
if( document.myform.customer.value == "" )
{
alert("Enter some value!"); return;
}
cookievalue = escape(document.myform.customer.value) + ";";
document.cookie = "name=" + cookievalue;
document.write ("Setting Cookies : " + "name=" + cookievalue );
}
</script>
</head>
<body>
<form name = "myform" action = ""> Enter name:
<input type = "text" name = "customer"/> <input type = "button" value = "Set Cookie" onclick = "WriteCookie();"/>
</form>
</body>
</html>
reading a cookie
– Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie.
– Use this string whenever you want to access the cookie.
– The document.cookie string will keep a list of name=value pairs separated by semicolons, where name is the name of a cookie
and value is its string value.
– document.cookie will return all cookies in one string much like: cookie1=value; cookie2=value; cookie3=value;
Ex: Program to display all contents of a cookie
<html>
<head>
<script type = "text/javascript">
function ReadCookie() {
var allcookies = document.cookie;
document.write ("All Cookies : " + allcookies );
deleting a cookie
- Sometimes you will want to delete a cookie.
- You don't have to specify a cookie value when you delete a cookie
- To do this, you just need to set the expiry date to a time in the past.
- You should define the cookie path to ensure that you delete the right cookie. Some browsers will not let you delete a cookie if you don't
specify the path
-
function DeleteCookie()
{
var now = new Date();
now.setMonth( now.getMonth() - 1 );
cookievalue = document.myform.customer.value + ";"
document.cookie = "name=" + cookievalue;
document.cookie = "expires=" + now.toUTCString() + ";"
document.write("Setting Cookies : " + "name=" + cookievalue );
}
Example: In this example, we will create a cookie that stores the name of a visitor.
• The first time a visitor arrives to the web page, he/she will be asked to fill in his/her name. The name is then stored in a cookie.
• The next time the visitor arrives at the same page, he/she will get a welcome message.
• For the example we will create 3 JavaScript functions:
• A function to set a cookie value
• A function to get a cookie value
• A function to check a cookie value
• First, we create a function that stores the name of the visitor in a cookie variable:
Ex: 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 + ";path=/";
}
Explanation:
• The parameters of the function above are the name of the cookie (cname), the value of the cookie (cvalue), and the number of days until
the cookie should expire (exdays).
• The function sets a cookie by adding together the cookiename, the
cookie value, and the expires string.
Explanation:
• Take the cookiename as parameter (cname).
• Create a variable (name) with the text to search for (cname + "=").
• Decode the cookie string, to handle cookies with special characters, e.g. '$'
• Split document.cookie on semicolons into an array called ca (ca = decodedCookie.split(';')).
• Loop through the ca array (i = 0; i < ca.length; i++), and read out each value c = ca[i]).
• If the cookie is found (c.indexOf(name) == 0), return the value of the cookie (c.substring(name.length, c.length).
• If the cookie is not found, return "".
4.3 Browser-opening a window, giving the new window focus, window position
4.4 changing the content of window, closing a window, scrolling a web page, multiple windows at once
<html>
<body>
<p id="demo"></p>
<script>
var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
var x = document.getElementById("demo");
x.innerHTML = "Browser inner window width: " + w + ", height: " + h + ".";
</script>
</body>
</html>
Other Window Methods
• window.open() - The open() method opens a new browser window, or a new tab, depending on your browser settings and the parameter
values.
• window.close() - close the current window
• window.moveTo() - move the current window
• window.resizeTo() - resize the current window
<html>
<body>
<button onclick="openWin()">Open "myWindow"</button>
<button onclick="closeWin()">Close "myWindow"</button>
<script>
var myWindow;
function openWin() {
myWindow = window.open("", "myWindow", "width=200,height=100");
myWindow.document.write("<p>This is 'myWindow'</p>");
}
function closeWin() { myWindow.close(); }
</script>
</body>
</html>
Scrolling Webpage
• The scrollTo() method scrolls the document to the specified coordinates.
• The scrollBy() method used to scroll a specified distance multiple times.
<html>
<head>
<style>
body { width: 5000px; }
</style>
</head>
<body>
<p>Click the button to scroll the document window to 500 pixels horizontally.</p>
<button onclick="scrollWin()">Click me to scroll horizontally!</button><br><br>
<script>
function scrollWin() { window.scrollTo(500, 0); }
</script>
</body>
</html>
4.5 creating a web page in new window, javascript in URLs, javascript security, timers, browser location and history
- JavaScript is designed as an open scripting language. It is not intended to replace proper security measures, and should never be used in place
of proper encryption.
- JavaScript has its own security model, but this is not designed to protect the Web site owner or the data passed between the browser and the
server.
- The security model is designed to protect the user from malicious Web sites, and as a result, it enforces strict limits on what the page author is
allowed to do. They may have control over their own page inside the browser, but that is where their abilities end.
- JavaScript cannot read or write files on users', though they can cause the browser to load remote pages and resources like scripts or images,
which the browser may choose to cache locally. They cannot create files on the server (except by communicating with a server side script that
creates files for them). The only thing they can store on the user's computer are cookies.
- They are allowed to interact with other pages in a frameset, if those frames originate from the same Web site, but not if they originate from
another Web site. Some browsers will even treat different port numbers on the same server as a different Web site.
- JavaScript cannot be used to set the value attribute of a file input, and will not be allowed to use them to upload files without permission.
- JavaScript cannot read what locations a user has visited by reading them from the location object, although it can tell the browser to jump
back or forward any number of steps through the browser history. It cannot see what other Web pages the user has open.
- JavaScript cannot access the cookies or variables from other sites.
- It cannot see when the user interacts with other programs, or other parts of the browser window.
- It cannot open windows out of sight from the user or too small for the user to see, and in most browsers, it cannot close windows that it did not
open.
- Most people who want to know about security with JavaScript are interested in producing password protected pages or sending encrypted data
to or from the user's computer.
- For true security, use SSL/TLS (HTTPS) and put all of your checks on the server. You could also use a security lockout if too many false
attempts are made, preventing brute force cracks. JavaScript cannot replace this functionality.
2. Concealing email address:It means hiding email address from unauthorized user. It is possible with the use of JavaScript.
JavaScript for concealing email address
function (user_email)
{
varavg, splitted, part1, part2;
splitted = user_email.split("@");
part1 = splitted[0];
avg = part1.length / 2;
part1 = part1.substring(0, (part1.length - avg));
part2 = splitted[1];
alert(part1 + "...@" + part2);
};
Timers
- A timer is a function that enables us to execute a function at a particular time.
- Using timers you can delay the execution of code so that it does not get done at the exact moment an event is triggered or the page is loaded.
- The window object allows execution of code at specified time intervals.These time intervals are called timing events.
The two key methods to use with JavaScript are
setTimeout(function, milliseconds):Executes a function, after waiting a specified number of milliseconds.
setInterval(function, milliseconds):Same as setTimeout(), but repeats the execution of the function continuously.
-
setTimeout()
-The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.
- Syntax :setTimeout(function, milliseconds, param1, param2, ...)
Here, function : The function that will be executed
milliseconds :The number of milliseconds to wait before executing the code.
If omitted, the value 0 is used
param1, param2, ...: Additional parameters to pass to the function
- Example:myVar = setTimeout(alertFunc, 3000);
setInterval()
- This method calls a function or evaluates an expression at specified intervals (in milliseconds).
- The setInterval() method will continue calling the function until clearInterval() is called, or the window is closed.The ID value
returned by setInterval() is used as the parameter for the clearInterval() method
- Syntax:setInterval(function, milliseconds, param1, param2, ...)
Here, function : The function that will be executed
milliseconds :The intervals (in milliseconds) on how often to execute the
code. If the value is less than 10, the value 10 is used
param1, param2, ...: Additional parameters to pass to the function
-Example :myVar = setInterval(alertFunc, 3000);
Window Screen
• The window.screen object contains information about the user's screen.
• The window.screen object can be written without the window prefix.
• Properties:
– screen.width
– screen.height
– screen.availWidth
– screen.availHeight
– screen.colorDepth: returns the number of bits used to display one color.
– screen.pixelDepth: returns the pixel depth of the screen
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Screen width is " + screen.width;
</script>
</body>
</html>
Window Location
• The window.location object can be used to get the current page address (URL) and to redirect the browser to a new page.
• The window.location object can be written without the window prefix.
Ex:
• window.location.href: returns the href (URL) of the current page
• window.location.hostname: returns the domain name of web host
• window.location.pathname: returns the path and filename of the current page
• window.location.protocol: returns the web protocol used (http: or https:)
• window.location.assign(): loads a new document
<html>
<body>
<h2>JavaScript</h2>
<h3>The window.location object</h3>
<p id="demo"></p>
<script> document.getElementById("demo").innerHTML =
"The full URL of this page is:<br>" + window.location.href;
</script>
</body>
</html>
<html>
<head>
<script>
function newDoc()
{
window.location.assign("https://www.w3schools.com")
}
</script>
</head>
<body>
<input type="button" value="Load new
document" onclick="newDoc()">
</body>
</html>
Window History:
Window Navigator:
The window.navigator object contains information about the visitor's browser.
The window.navigator object can be written without the window prefix.
Properties:
1. navigator.cookieEnabled: returns true if cookies are enabled, otherwise false
2. navigator.appName:returns the application name of the browser
3. navigator.appCodeName: returns application code name of browser
4. navigator.product: returns product name of the browser engine
5. navigator.appVersion:returns version information about the browser
6. navigator.userAgent: returns the user-agent header sent by the browser to the server
7. navigator.platform:returns the browser platform (operating system):
8. navigator.language: returns the browser's language:
9. navigator.online: returns true if the browser is online:
10. navigator.javaEnabled():method returns true if Java is enabled