You are on page 1of 31
cookies, Deletin Syllabus : rookie value, Writing a cookie value, Creating @ 8 8 can i ding a c d 4.1. Cookies — Basic of cookies, loa ‘Setting the expiration date of cookie. focus, Wit Giving the new window page, Multiple windows at once, Browser location and History: indow position, Changing the Senter of wind 42. Browser ~ Opening a window, ‘Creating a web page in new window, Javasei. Closing a window, Scroling a ws in URLs, JavaScript security, Timers, = ‘The user information present in web pages can be stored by using cookie.Cookie is a small piece of information sex: from the website and stored in a file on the user's computer. The information sent from the website is specific to a user is stored by the user’s web browser, and web browser can access that information. 4.1 Cookies 4.1.1. Basic of Cookies Cookie works as follows Storing information : When user visits the website the basic information such as username and password can be stored in a cookie. Accessing information : [5 Wsername = "student ee i Sane t website are added to the request. In this way t ation Cookie isa small text fle stored in the subol When a browser requests a website, cc Cookles belonging t website gets the required data to remember the user rats fe ir of the browsers installation folder. it contains folowing data, - Aname-value pair — An expiry date for that cookie ~The website/Domain name _ ido Setipting Language (MSBTE) gent Cookies and Browser Data 2 Types of Cookies ad ze three types of cookies, re ip session cookle iy reritentcooke (@) Third party cookie (9 Session Cookies Sesion cookies are temporary cookies that remember users online activities throughout a session. i.e. it remember the information when a user logged in until logout or when user close the web page, When « user gets logged out the session cookie gets expired. (t) Persistent Cookies Persistent cookies assigned an expiration date. It does not get expired until it reaches to the expiration date. It does not expe with users logged out and closing web page. It is stored in subfolder in folder of browsers installation, JavaScript can create, read and delete cookies using document.cookie property. 41.3 Creating a Cookie Sue ee 8 rhe Tocreate a cookie we need to assign a value to cookie by using document.cookie as follows : document.cookie = “username = student’; \ “3 Name Value Completion of Sentence (Semicolon) ‘username’ by using assignment operator ‘=’ and ‘students assigned to nam = me shown above, the sake ae (:)-The name value pair with double quote (" name = value *) is assigned to ‘nce is terminated with a semi (i). ¢d when the browser is closed.You can also add an expiry date ie f cookie Is deletes rent.cookie.By default the above type Oo! ‘Othe cookie in UTC time format,as follows :~ : document.cookie = “username = studontioxpires = Th 4 Jul 2019 11:30:00 UTC" cument.cookie = | | \ va i Delimiter (Semicolon) Namo Valu Completion of Sentence el Name value ir of name value tothe cookle you need to separate the pairs a d for the sentence completion and also for the pair assign more than oF eee eee ies lealon Is ited by the delimiter, The sentence completion it us sem : With the delimiter, here semicolon (;) is used: Th Tn double quotes €P3 Separation. All the name value palrs are assigned ible quot Semicolon is provided after the closing of the dou : Cookies and Bro St 43 q Gliont Side Scripting Language (MSBTED io a cookie Program 4.1.1 : Write a JavaScript code to create @ _ ae G I [ eae : cee ‘text’ id='username'> \Enter Username: : [sfhtmi> HGS ae 'n Program 4.1.3, we enter the cookie value which we want to delete. On button click deleteCookie() function is called. ‘The value of the cookie Is stored to the cookie value variable. Then we ass the value of cookie to the name along with the “lation date by using statement ‘document.cookie = "username: "*cookie_value+"expires=Thu, 01 Jan 1970 00:00:01 GMT"here we are assign the old date to the expires property of cookie. This will delete the cookie. Tea va You can extend the life of a cookie by setting @ new expiration date to the cookie. This can be done by setig the ‘expires’ attribute to a new date and tiie. The new date object is obtained by using ‘new Date()’. The Date ks following function to get the month of the date to set the month of the date and to format the date string. 1. __getMonth(): this function returns the month of the current date object, 2. _ setMonthi) : this function set the month to the current date object 3. toUTCString() : this function formats the date in the standard format to ‘Set to the expiration date of the cookie. Program 4.1.4 : Write a JavaScript code to set the expiration date of cookie, ‘Solution : | function changedate() { jar now = new Date(); - now.setMonth( now.getMonth() + 1); var cookie_value = username.value; : | document.cookie = "username=" + cookie_value-+"sexpires=" | alert ("Expiry Date of Cookie changed :" + "username=" + now.toUTC + cookie value); | | yg lent Side Seripting Language (MSBTE) 48 ( . ‘ tener cookie name: 4 ut type = "button" value = "Extend Expiry Date" onclick = "changedate()"/> Cookios and Browser Data toal> output: Expiry Date of Cookies changed: usemame=Admin Fence] In Program 4.1.4, we change the expiration date by assigning the new date to the expires attribute of the cookie. Fitst we prepare the date by using date object and invoking getMonth() and setmonth() functions on it. Then that date is formatted by using toUTCString() function of date object before assigningto the cookie. 4.2 Browser We can perform various operation with browser window in JavaScript. We can opena new window from currently running javascript. We can give focus to the new window-We can set the position, size and location of new window. We «an change the content of the window We also cen perform operation such as scroling @ webpage, multiple window at 2 slance, creating a webpage in new window and closing a window, 4.2.1 Opening a Window 1 How to open a window. Deseribe various style of window. Fa. How to open a window. Explain with example, We can open a new window from current window on ed click, oo ‘©peration with the browser window we have window object. The window object has Varo" en ei to work with the browser window. To open @ new window from current window we use the copen() of the wint : Open() function; sindow trom erent ndow- BINWERES ON Window objet, This function is used to open a new ‘Syntax : Seren Be 49 Client Side Scripting Language (MSBTE) _ window. nin new Wil url sit specifies the URL of the new page Eo 1° be open inne’ Itis optional. 1 of the window. ; : crolibar, toolbar, height, width, location, etc ths Name : itis used to set the nam! farious parameters such as $ “style : Style of the window has vé values. optional. ult if we do not provide optional parameter values, then the window gets defa! There are various styles of window as follows Description Style To display the browser toolbar toolbar= yes|no|1[0 status= yesno]1]0 | Toadda status bar titlebar= yes|no|1|0 | To display the title bar To display the menubar yes|no|1]0 To display the browser in full screen mode menubat fullscreen=yes|no|1]0 resizable=yes|no|1|0_ | To determine whether the window is resizable scrollbars= yes|no|1[0 | To display scroll bars The height of window minimum value is 100 height=pixels width=pixels The width of the window left=pixels The left position of the window top=pixels Top position of window Program 4.2.1: Write a JavaScript to open a new window. Solution : ‘ > Click to open a new window

> jpting Language (MSBTE) 4A et = Cookies and Browser Data on | FeJavascript/cookie/openhtml [+ Click to open a new window ay In Program 4.2.1, the statement'window.open(",”","width=200,height=100");’ is used to open the window. This sstement will execute when the openWindow/) is called on button click. 42.2 Giving New Window Focus When we open another window then if we want to give the focus to that window then focus() is used. Program 42.2: Write a JavaScript code to set the window focus. Cookies and Bronte, ait SF Clon side Sorping Language (MSBTE) Output : + Click to open a new window | [open new window |p : he statement‘window.open("’,", "width=200,height=100");” is used to open the window, indow. These statements will execute when the openWindoy), In Program 42.2, tl statement ‘this focus();‘provide the focus to the new wi called on button click. 4.2.3. Window Position When we create a new window, we can set the specified position to the new window. The attributes left and topzz used to specify the position of the new window. We pass the values to these attributes in window.open() function x parameters. | Program 4.2.3: Write a JavaScript to set the window position. Solution : | pody> : |

Click to open a new window

"button" value = "open new window" onclick = "openWindow()"/> | w nt 08, sgoripting Language (MSBTE) ag Z Cookies and Browser Data ut! ae iS “~» = =| | Click to open a new window In Program 42.3, the statement ‘window.open(”","","left=0, top=0, width=200,height=100")is used to open a window and display it to the specified position. The left and top properties specify the x and y coordinates respectively. 424 Changing the Content of Window {How fo change the c 1 Howto change the content of whole window? Explain with example. (2. How to change the content of a particular element of @ webpage? Explain with exemple. Youcan change the content of window dynamically. You can change content in two ways; first changing the content of vihol window, second changing the content of a specific element present in the window, 42.4.1 Changing the Content of whole Window You can change the content of whole window by using document.write() function. This function is used to override the content of the webpage. Program 4.2.4: Write a JavaScript code to change the content of whole window. Solution : jshtmi> \sheads ser aa ‘Script type = "text/javascript"> function changeContent() { document tite-

-

After licking the Button: New Content

"); ; write ; } Sseript> Tettooaieagt Cooklos and Browser a N¥_ciiont Sito Scripting Language (MSBTE) f=fiead> j J

Click to cha

Atter clicking the Button: New Content

");’statement Is useq 0 ge the content of whole. Window

*Change Content” onclic icking the Button: Old Content

k= "changeContent()"/> In Program 4.2.4 change whole content of the webpage. Output: Co L @ filey/e:/ Click to change the content of whole Window ‘YE/lavescript/cookie/content2.hi: X fo) 9@ [0 tenes 4.2.4.2 ‘Changing the Content of a Specific Element In Wi indow We can change the content of various el lem chore ee content of a specific element of a window sialon e element you can use ‘id’ . . attribute. Ther JavaScript. After getting the access of the el ae element as given below. =a such You need to previa enn division, table etc, if you want '¢ unique id to that element. To provide thé! id (pion: Ss Sotbthg Language (MSSTE 14 Cookies and Browser Data ‘& JavaSerpt code to change the content of a specific element in window. leqrigt ope = Textjavecript”> fonction changeContent() { document getElementByld("para’) innerHTML= "After clicking the Button: New Content"; ‘

Click to change the content of paragraph

“pare’> Before Clicking the Button: Old Content

| Pessveasigteostiel contents X SS - > Ee O@ fleyfe: ~Ow » Click to change the content of paragraph (Ghange conte | ‘After clicking the Button: New Content Cookies and Boren m™ 4.2.5, we create a paragraph by using

tag with ID “para”. This ‘ID’ is used to get the paragraph Cony Symcrigt By passing the ID ‘para’ to document.getElementBylD(“para”) function. On that control we Use innern, \ srry which allocates the new content to the paragraph. Thus only paragraph content Is changed Instead of a werrsaes Closing the Window Howto close a window? Explain with example. Y the which “The close) function is used to close the window. By using lose) functions we can only close the Which we open the help of opent) function. Program 4.2.6 : Write a JavaScript code to close a window. Solution :

Click to open a new window

[ a cert Sid Seiptng Language ISETE) 416 Gooklos and Browsor Data Output: FEsflavasctipt/cookie/close htm! X | eae | 1o > CO fiewyre: “Ow » e@ | Q. about:blank Click to open anew window [@!Mozill. - © [open new window] In Program 4.2.6, we create a variable. by using statement ‘var new_win;’. The statement ‘new_win = window.open("","",“width=200,height=100"),” is used to open a new window and store the instance of that window to the variable ‘new_win’. Then to close the newly created window we need to invoke the close() function on the window instance stored in ‘new_win‘variable by using statement ‘new_win.close();’. 4.26 Scrolling a Webpage ‘We can scroll a webpage vertically and horizontally. To scroll webpage we use scrollTo(Jand scollBy() functions. 4.2.6.1 scrollTo() The scrollTo() function is used to scroll the webpage to the fix position specified by x and y coordinates passed as Parameters to the function. ‘Syntax : [windswscroitToupos ypes) Parameters : %P0s :The coordinate to scroll to, along the x-axls (horizontal), n pixel ‘Yeo: The coordinate to scroll to, along the y-axis (vertical), in pixels, ‘The seolo() function scrolls the document to the specified coordinates. Cliont Sido Scripting Language (MSBTE) s and Browser Da, tito » JavaScript codo to scroll the window to the particular position. Program 4. Solution: zhimi> |

Click to scroll window

A

B

C

D

|

E

e 1® files/// “yD Click to scroll window [ ween AEfavascript/ec 1 Side Scripting Language (MSBTE) 418 Cookies and Browser Data hae x i i ----Window is Scrolled. | In Program 4.2.7, statement ‘scrollTo(0, 200);'is used to scroll the document in the web page ver 200 pixels, as we mentioned the y coordinate 200, 42.6.2 scrollBy() The scrollBy() function is used to scroll a specified distance in pixel multiple times.The scrollBy() function scrolls the document in the webpage by the specified number of pixels. ‘Syntax : fiindow.scrollBy(xnum, ynum) 7 Parameters : xnum : it specifies the number of pixels to scroll by, along the x-axis (horizontal). Positive values will scroll the ‘webpage to the right, while negative values will scroll the webpage to the left. ‘ynum :it specifies the number of pixels to scroll by, along the y-axis (vertical). Positive values will scroll the webpageto bottom, while negative values scroll to top. Program 4.2.8 : Write a JavaScript code to scroll a window by specified pixels. |

Click the button to op’ "openWindows()" value= "Open Windows" > Output : |< [am > toy 7 > @\|oe Click the button to open multiple windows. FG: Mozilla Fiz, — sal + @ Mozilla Fir, — FO = _Mozil (Open Windows | 'n Program 4.2.20, the statement window.’pen{"",™, "width=200,height=100")rs used within for loop to open mut? windows at the same time, 4.2.8 Creating a Webpage in New Window .Q. “How to create a webpage in new window? Explain with example, We can create a webpage in new window with the help of write function of window object. We can provi Content of the webpage inside the write() function. The html code as a string parameter is passed to the write) func We can provide tags such aschtml>,, , <body>, <p>, <div>, <hi>, <br>, etc. The write function is capable” recognizing the html content and it will convert the html passed as string to the webpage. 4-22 Cookies and Browser Data wo ‘Side Scripting Language (MSBTE) program 42.11 Wee a JavaScript code to create a webpago in new window. solution: fzhiml> <head> eseript type = "text/javascript"> function openWindow() { ‘yar new_Wwin = window.open("New Window","","width=300,height=300"); new. win.document.write("<htnil>"); new_win.document.write("<head>"); new_win.document.write("<title>"); new swin.document.wvrite("New Window"); new_win.document.write(""); ‘new_win.document.write(""); new. win,document.write(""); new win.documentwrite("

Welcome to the New Window.

"); ‘new twin.document.write("

This Webpage is created in New Window.

"); new_win.document.write(""); new_win.documentwrite(""); : ; j g : as ‘ ose ae ; Bees

Click to open a new window

' /

Click to get The Path of the Web Pagec/p> pls has ae Cookies and Browser Data. ent Sido Sorinting Language (MSBTE) 4-20 alue = "Get the Path” onclick = "displayFunetion()3"/> Click to get The Path of Fthe Web Page | (camera) | The webpage is located at: /pathname-html In Program 4.2.14, path name is provided by ‘window. location.pathname’. Program 4.2.15 : Write a JavaScript code to get the Hostname. function iepagrunciong document, getElementByld( a |"+window location. hostname; ‘p> Click to get The Host of the Web Page

input type = *button’ value = "Get the Host" onclick = "displayFunction()s"/> : SP. id = "para'>

Cookies and Brows Oa Cllont Sido Soripting Language (MSE. Output : ane Tae si EB locate: X | ea! call <€7e¢ 0 localhost/hostname.html Click to get The Host of the Web Page | [[Get the Host In Program 4.2.15, ‘wi ‘ indow.location.hostname;‘gives the host name. here we are using local host to run the script, Program 4.2.16 : Write a JavaSoript code to get the Protocol. ys ‘Serpting Language (MSBTE) 430 Cookies and Browser Data tocalbs x loca locas x | + | € > S| O tocathost/protocot.htmi ‘ Click to get The protocol of the Web Page {Get the protocol | The protocol of the webpage is: http: tn Program 42.6, ‘window:location.protocol‘gives the protocol name. Here we are using local host so that we are getting the http protocol. If we run a simple html file in a browser, then we will get the file protocol. 4212.2 History ‘The window.history object contains the record of URLs visited by the user within a browser window. The history object isa partof the window object so that itis accessed by window.history, is used to return the number of URLs in the list of history. Methods : ‘back{): itis used to load the previous URL in the history list. forward() :it is used to load the next URLin the history list. 0f)zitis used to load a specific URL from the history list. Program 4.2.17 : Write a JavaScript code to get a history list. Cookies and Browse bee) ss "ne) 2 onslick Output : In Program 4.2.27, statement ‘window. history.back/);is used to get previous URL from history list and ‘window.history,forwords sed to get the next URL from history list. gad

You might also like