Sie sind auf Seite 1von 121

JAVA SCRIPT

Introduction
HTML pages are static They do not react to events There is no programming involved at all Attempts were made to add interactivity to HTML pages This was done both at client (web browser) side as well as the server side Javascript is a client side technology

Basic Concepts
Earlier there were other technologies like VB script and Jscript, however these technologies are now obsolete Java script is an interpreted language It can be directly embedded inside the HTML pages or it can be kept in a separate file(with file extension js) It is supported by all major browsers

Basic Concepts
Java and Javascript have nothing in common, except for naming

Features of Javascript
JS is a scripting language with a very simple syntax Can produce dynamic text into an HTML page Reacting to events Read and write HTML elements Validate data

JavaScript Guidelines
JavaScript is Case Sensitive A function named "myfunction" is not the same as "myFunction" and a variable named "myVar" is not the same as "myvar". White Space JavaScript ignores extra spaces. You can add white space to your script to make it more readable. The following lines are equivalent: name="Hege"; name = "Hege";

JavaScript Guidelines
Break up a Code Line You can break up a code line within a text string with a backslash. The example below will be displayed properly: document.write("Hello \ World!"); However, you cannot break up a code line like this: document.write \ ("Hello World!");

Javascript example
<html> <body> <script type=text/javascript> document.write(Hello World); </script> </body> <html> CLICK TO SEE THE OUTPUT

Controlling JS Execution
Javascript is a part of the HTML page Contained inside <script>..</script> tags Document is the name of the object Write is the method of that object
Writing a script in the head section Executes only when explicitly called

Writing a script in the body section

Executes automatically on its own

JS Example
JS example in head section JS example in body section

External Java Script


<html> <head> </head> <body> <script src=myscript.js></script> </body> </html>

Declaring Variables
Local Variables: variables inside a function Global Variables: Variables outside a function Example1 Example2

Comments in JS
Single Line Comment
//

Multiple Line Comment


/* .. */

HTML in JS
Example

Java Script Operators


Operator Classification Arithmetic Assignment Comparison Logical List of Operators +, -, *, /, %,++, -=,+=,-=,*=,/=,%= =,<,>,<=,>=,!= &&, ||,!

Functions in JS
All the functions should be defined in the <head> section , right at the beginning of the HTML page A function can receive arguments, or it can also be a function that does not expect any arguments A function is declared using a keyword called as function followed by the name of the function

Functions in JS
Any arguments expected by the function are listed inside the paranthesis, separated by commas A function can return single value by using the return statement The function does not have to mention its return data type in the function declaration

An example on function
function total(a,b) { result=a+b; return result; }

Conditional Statements
If If-else switch

LOOP
In JavaScript, there are three different kind of loops: for - loops through a block of code a specified number of times while - loops through a block of code while a specified condition is true The do...while Loop

Syntax for FOR LOOP


for (var=startvalue;var<=endvalue;var=var+incre ment) { code to be executed } example

Syntax for WHILE LOOP


while (var<=endvalue) { code to be executed } example

Syntax for do while loop


do { code to be executed } while (var<=endvalue); example

JavaScript Break and Continue Statements


The break Statement The break statement will break the loop and continue executing the code that follows after the loop (if any). example

The continue Statement The continue statement will break the current loop and continue with the next value example

JS Pop Up Boxes
Alert Box Alert Box with Line Breaks Prompt Box Confirm box

Events
By using JavaScript, we have the ability to create dynamic web pages. Events are actions that can be detected by JavaScript. Every element on a web page has certain events which can trigger a JavaScript. For example, we can use the onClick event of a button element to indicate that a function will run when a user clicks on the button. We define the events in the HTML tags.

Events
Examples of events:
A mouse click A web page or an image loading Mousing over a hot spot on the web page Selecting an input field in an HTML form Submitting an HTML form A keystroke

Note: Events are normally used in combination with functions, and the function will not be executed before the event occurs!

onLoad and onUnload


The onLoad and onUnload events are triggered when the user enters or leaves the page. The onLoad event is often used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information. Both the onLoad and onUnload events are also often used to deal with cookies that should be set when a user enters or leaves a page.
For example, you could have a popup asking for the user's name upon his first arrival to your page. The name is then stored in a cookie. Next time the visitor arrives at your page, you could have another popup saying something like: "Welcome John Doe!".

What is a Cookie?
A cookie (also tracking cookie, browser cookie, and HTTP cookie) is a small piece of text stored on a user's computer by a web browser. A cookie consists of one or more name-value pairs containing bits of information such as user preferences, shopping cart contents, the identifier for a server-based session, or other data used by websites.

onFocus, onBlur and onChange


The onFocus, onBlur and onChange events are often used in combination with validation of form fields. Below is an example of how to use the onChange event. The checkEmail() function will be called whenever the user changes the content of the field: <input type="text" size="30" id="email" onchange="checkEmail()">

onSubmit
The onSubmit event is used to validate ALL form fields before submitting it. Below is an example of how to use the onSubmit event. The checkForm() function will be called when the user clicks the submit button in the form. The function checkForm() returns either true or false. If it returns true the form will be submitted, otherwise the submit will be cancelled: <form method="post" action="xxx.htm" onsubmit="return checkForm()">

onMouseOver and onMouseOut


onMouseOver and onMouseOut are often used to create "animated" buttons. Below is an example of an onMouseOver event. An alert box appears when an onMouseOver event is detected: <a href="http://www.w3schools.com" onmouseover="alert('An onMouseOver event');return false"><img src="w3s.gif" alt="W3Schools" /></a>

JavaScript Special Characters


Code \' \" \& \\ \n \r \t \b \f Outputs single quote double quote ampersand backslash new line carriage return tab backspace form feed

JavaScript Objects Introduction


JavaScript is an Object Oriented Programming (OOP) language. An OOP language allows you to define your own objects and make your own variable types. An object has properties and methods.

Properties
Properties are the values associated with an object. In the following example we are using the length property of the String object to return the number of characters in a string:

Example of Length Property


<script type="text/javascript"> var txt="Hello World!"; document.write(txt.length); </script> The output of the code above will be: 12

Methods
Methods are the actions that can be performed on objects. In the following example we are using the toUpperCase() method of the String object to display a text in uppercase letters:

Example on Method
<script type="text/javascript"> var str="Hello world!"; document.write(str.toUpperCase()); </script> The output of the code above will be: HELLO WORLD!

JavaScript String Object


String Length Style Strings Index_of Match_string Replace_string

Strings Concatenating strings (+)


var a = 'Hello world!'; var b = 'I am a JavaScript hacker.'
document.write(a + b);

Out put
Hello world!I am a JavaScript hacker.

indexOf
var a = 'Hello world!'; document.write(a.indexOf('w'))
Gives 6

document.write(a.indexOf('o'))
gives 4

document.write(a.indexOf('o',5));

lastIndexOf
There's also lastIndexOf which gives the last occurrence of the character or combination. It otherwise works exactly as indexOf. This var b = 'I am a JavaScript hacker.' document.write(b.lastIndexOf('a')) gives 19 because that's the index of the last 'a' in the string.

charAt
charAt() gives you the character at a certain position. For instance, when you do var b = 'I am a JavaScript hacker.' document.write(b.charAt(5)) gives 'a', because that's the character at the sixth position (remember, first character is 0!).

split
split() is a specialized method that you need sometimes. It allows you to split a string at the places of a certain character. You must put the result in an array, not in a simple variable. Let's split b on the spaces. var b = 'I am a JavaScript hacker.' var temp = new Array(); temp = b.split(' ');

output
Now the string has been split into 5 strings that are placed in the array temp. The spaces themselves are gone. temp[0] = 'I'; temp[1] = 'am'; temp[2] = 'a'; temp[3] = 'JavaScript'; temp[4] = 'hacker.';

substring
substring is used to take a part of a string. Syntax is substring(first_index,last_index). So for instance var a = 'Hello world!'; document.write(a.substring(4,8));

output
gives 'o wo', from the first 'o' (index 4) to the second one (index 7) Note that the 'r' (index 8) is not part of this substring.

substring
var a = 'Hello world!'; document.write(a.substring(4)); This gives the whole string from the character with index 4 on: 'o world!'.

substr
There is also a method substr() that works slightly differently. Instead of the second number being an index number, it gives the number of characters. So document.write(a.substr(4,8));

output
starts at the character with index 4 ('o') and then gives 8 characters, so the output is o world!

toLowerCase and toUpperCase


var b = 'I am a JavaScript hacker.' document.write(b.toUpperCase()) gives 'I AM A JAVASCRIPT HACKER.'.

Date & Time


getTime() - Number of milliseconds since 1/1/1970 @ 12:00 AM getSeconds() - Number of seconds (0-59) getMinutes() - Number of minutes (0-59) getHours() - Number of hours (0-23) getDay() - Day of the week(0-6). 0 = Sunday, ... , 6 = Saturday getDate() - Day of the month (0-31) getMonth() - Number of month (0-11) getFullYear() - The four digit year (1970-9999)

<h4>It is now <script type="text/javascript"> var currentTime = new Date() var month = currentTime.getMonth() + 1 var day = currentTime.getDate() var year = currentTime.getFullYear() document.write(month + "/" + day + "/" + year) </script> </h4>

Instead of displaying the date, display the format you might see on a typical digital clock -- HH:MM AM/PM (H = Hour, M = Minute).

Code
<script type="text/javascript"> var currentTime = new Date() var hours = currentTime.getHours() var minutes = currentTime.getMinutes() if (minutes < 10){ minutes = "0" + minutes } document.write(hours + ":" + minutes + " ") if(hours > 11){ document.write("PM") } else { document.write("AM") } </script>

Creating Arrays in JavaScript


var array_name = new Array(number_of_elements) array_name[0] = "Array element"

Arrays
var faq = new Array(3) faq[0] = "What are JavaScript arrays" faq[1] = "How to create arrays in JavaScript?" faq[2] = "What are two dimensional arrays?"

Math Object & Methods


abs(a) - Returns the absolute value of a acos(a) - Returns the angle in radians that has a cosine of the passed value asin(a) - Returns the angle in radians that has a sine of the passed value ceil(x) - Rounds up the value of "a" to the next integer floor(a) - Rounds the passed value down to the next lowest integer.

Math Methods
max(a,b) - Returns the larger value of a or b. min(a,b) - Returns the lower value of a or b. pow(a,b) - Takes the value of a to the power b.

JavaScript Window Object


The JavaScript Window Object is the highest level JavaScript object which corresponds to the web browser window

Window object Properties


clientInformation closed - A boolean value that indicates whether the window is closed. defaultStatus - This is the default message that is loaded into the status bar when the window loads. window.defaultStatus = "Click on a link on the left to navigate this website."

Window Object Properties


status - The status bar is the bar on the lower left side of the browser and is used to display temporary messages. The below example will write a message to the status bar window.status = "This message will display in the window status bar."

Example on Window Status


<a href= " target="_top" onMouseOver="window.status='This will take you to the Home Page' ;return true" onMouseOut="window.status='Hey! You are not holding the mouse on the Home Button!';return true"> <img SRC=" ALT="Home" VSPACE=3 BORDER=0 height=35 width=120></a>

Window Object Methods


alert("message") - The string passed to the alert function is displayed in an alert dialog box. blur() - This function will take the focus away from the window clearInterval(interval) - Clear the timeout interval.

Window Object Methods


close() - This function will close the current window or the named window. window.close() focus() - This function will give the focus to the window. moveBy(x,y) - The window is moved the specified number of pixels in the X and Y direction. moveTo(x,y) - The window is moved to the specified X and Y pixel location in the browser.

Window Object Methods


open("URLname","Windowname",["options"]) A new window is opened with the name specified by the second parameter. The document specified by the first parameter is loaded. The options are not required, and may be set to values of yes or no Many options are set to default values depending on whether others are set

Open method Options


For example, if the width and height are specified, the resizable option is set as default to no. Also if the toolbar is off, the menubar is set to default of no. The options are:
alwaysRaised - If yes, the created window is raised. directories - The value of yes or no determines if the window shows directory buttons or not. height - Specifies the window height in pixels. This is set to an integer value, rather than yes or no. left - Specifies the distance in pixels the new window will be placed from the left side of the screen. This is set to an integer value, rather than yes or no.

Open method Options


location - The value of yes or no determines if the window has a location displayed on the address line (or has an address line) or not. menubar - The value of yes or no determines if the window has a menubar or not. outerWidth - Specifies the outer window width in pixels. This is set to an integer value, rather than yes or no. outerHeight - Specifies the outer window height in pixels. This is set to an integer value, rather than yes or no. resizable - The value of yes or no determines if the window can be resized by the user or not

Open method Options


status - The value of yes or no determines if the window has a status bar or not. scrollbars - The value of yes or no determines if the window has scroll bars or not. toolbar - The value of yes or no determines if the window has a toolbar or not. top - Specifies the distance in pixels the new window will be placed from the top of the screen. This is set to an integer value, rather than yes or no. width - Specifies the window width in pixels. This is set to an integer value, rather than yes or no. z-lock - If yes, the created window is in the background.

Example on open method


Example: <script language="JavaScript"> open("javahere.html","test", "toolbar=no,menubar=no,width=200,height=2 00,resizable=yes") </script> example

Example on setTimeout
setTimeout(function(),milliseconds,[functargs]) Used to call a function after the specified time in milliseconds. If you put the following code in your HTML body start tag: <body onLoad="timeID = setTimeout('showMessage()',4000)"> And put this code inside your HEAD element: <SCRIPT LANGUAGE="JavaScript"> function showMessage() { alert("It has been 4 seconds since this page loaded.") } </SCRIPT> Your page will display the alert message four seconds after it loads.

Events
onafterupdate onBeforeunload onBeforeupdate onBlur onClick ondblclick onError onerrorupdate onFocus onhelp onkeydown onkeypress

Events
onkeyup onLoad onmousedown onmousemove onmouseout onmouseover onmouseup onreadystatechange onresize onrowenter onrowexit onscroll onselectstart onUnload

JavaScript History Object


The JavaScript History Object is property of the window object. Properties
current - The current document URL. length - The number of entries in the history object. next - The URL of the next document in the history object. previous - The URL of the last document in the history object.

History Object Methods: BACK


Methods back() - Go to the previous URL entry in the history list. This does the same thing as the browser back button. The following HTML code creates a back button: <FORM> <INPUT TYPE="button" VALUE="Go Back" onClick="history.back()"> </FORM>

History object method: FORWARD


forward()- Go to the next URL entry in the history list. This does the same thing as the browser forward button. This is only effective when there is a next document in the history list. The back function or browser back button must have previously been used for this function to work. The following HTML code creates a forward button: <FORM> <INPUT TYPE="button" VALUE="Go Forward" onClick="history.forward()"> </FORM>

History Object Method: GO


go(relPos | string) - This function will accept an integer or a string. If an integer is used, the browser will go forward or back (if the value is negative) the number of specified pages in the history object (if the requested entry exists in the history object). The following example will move the browser back one page. <FORM> <INPUT TYPE="button" VALUE="Go Back" onClick="history.go(-1)"> </FORM>

JavaScript Form Object


The JavaScript Form Object is a property of the document object. This corresponds to an HTML input form constructed with the FORM tag. A form can be submitted by calling the JavaScript submit method or clicking the form submit button.

Form Object Properties


action - This specifies the URL and CGI script file name the form is to be submitted to. It allows reading or changing the ACTION attribute of the HTML FORM tag. elements - An array of fields and elements in the form. encoding - This is a read or write string. It specifies the encoding method the form data is encoded in before being submitted to the server.
It corresponds to the ENCTYPE attribute of the FORM tag. The default is "application/x-www-form-urlencoded". Other encoding includes text/plain or multipart/form-data.

Form Object Properties


length - The number of fields in the elements array. I.E. the length of the elements array. method - This is a read or write string. It has the value "GET" or "POST". name - The form name. Corresponds to the FORM Name attribute. target - The name of the frame or window the form submission response is sent to by the server. Corresponds to the FORM TARGET attribute.

Form Objects : Buttons


button - An GUI pushbutton control. Methods are click(), blur(), and focus(). Attributes:
name - The name of the button type - The object's type. In this case, "button". value - The string displayed on the button.

Checkbox
checkbox - An GUI check box control. Methods are click(), blur(), and focus(). Attributes:
checked - Indicates whether the checkbox is checked. This is a read or write value. defaultChecked - Indicates whether the checkbox is checked by default. This is a read only value. name - The name of the checkbox. type - Type is "checkbox". value - A read or write string that specifies the value returned when the checkbox is selected.

FileUpload
FileUpload - This is created with the INPUT type="file". This is the same as the text element with the addition of a directory browser. Methods are blur(), and focus(). Attributes:
name - The name of the FileUpload object. type - Type is "file". value - The string entered which is returned when the form is submitted. example

Hidden
hidden - An object that represents a hidden form field and is used for client/server communications. No methods exist for this object. Attributes:
name - The name of the Hidden object. type - Type is "hidden". value - A read or write string that is sent to the server when the form is submitted.

Password
password - A text field used to send sensitive data to the server. Methods are blur(), focus(), and select(). Attributes:
defaultValue - The default value. name - The name of the password object." type - Type is "password". value - A read or write string that is sent to the server when the form is submitted.

Radio
radio - A GUI radio button control. Methods are click(), blur(), and focus(). Attributes:
checked - Indicates whether the radio button is checked. This is a read or write value. defaultChecked - Indicates whether the radio button is checked by default. This is a read only value. length - The number of radio buttons in a group. name - The name of the radio button. type - Type is "radio". value - A read or write string that specifies the value returned when the radio button is selected.

Reset
reset - A button object used to reset a form back to default values. Methods are click(), blur(), and focus(). Attributes:
name - The name of the reset object. type - Type is "reset". value - The text that appears on the button. By default it is "reset".

Select
select - A GUI selection list. This is basically a drop down list. Methods are blur(), and focus(). Attributes:
length - The number of elements contained in the options array. name - The name of the selection list. options - An array each of which identifies an options that may be selected in the list. selectedIndex - Specifies the current selected option within the select list type - Type is "select".

Submit
submit - A submit button object. Methods are click(), blur(), and focus(). Attributes:
name - The name of the submit button. type - Type is "submit". value - The text that will appear on the button.

text
text - A GUI text field object. Methods are blur(), focus(), and select(). Attributes:
defaultValue - The text default value of the text field. name - The name of the text field. type - Type is "text". value - The text that is entered and appears in the text field. It is sent to the server when the form is submitted.

Text Area
textarea - A GUI text area field object. Methods are blur(), focus(), and select(). Attributes:
defaultValue - The text default value of the text area field. name - The name of the text area. type - Type is textarea. value- The text that is entered and appears in the text area field. It is sent to the server when the form is submitted.

Form Object Methods


reset() - Used to reset the form elements to their default values. submit() - Submits the form as though the submit button were pressed by the user.

Events
onReset onSubmit

Passing Values to Javascript


<SCRIPT> function verifyInput(textObject) { if (textObject.value == 'CA' || textObject.value == 'AZ') { alert('Nice input') } else { document.myForm.reset() } } </SCRIPT> <FORM NAME="myForm" onReset="alert('Please enter CA or AZ.')"> Enter CA or AZ: <INPUT TYPE="text" NAME="state" SIZE="2" onChange=verifyInput(this)><P> </FORM>

Validating radio buttons


if ( ( document.contact_form.gender[0].checked == false ) && ( document.contact_form.gender[1].checked == false ) ) { alert ( "Please choose your Gender: Male or Female" ); valid = false; }

Validating drop-down lists


if ( document.contact_form.age.selectedIndex == 0 ) { alert ( "Please select your Age." ); valid = false; }

Validating checkboxes
if ( document.contact_form.terms.checked == false ) { alert ( "Please check the Terms & Conditions box." ); valid = false; }

JavaScript Navigator Object


The JavaScript navigator object is the object representation of the client internet browser or web navigator program that is being used. This object is the top level object to all others.

Navigator Properties
appCodeName - The name of the browser's code such as "Mozilla". appMinorVersion - The minor version number of the browser. appName - The name of the browser such as "Microsoft Internet Explorer" or "Netscape Navigator". appVersion - The version of the browser which may include a compatability value and operating system name. cookieEnabled - A boolean value of true or false depending on whether cookies are enabled in the browser. cpuClass - The type of CPU which may be "x86"

Navigator Properties
mimeTypes - An array of MIME type descriptive strings that are supported by the browser. onLine - A boolean value of true or false. platform - A description of the operating system platform. In my case it is "Win32" for Windows 95. plugins - An array of plug-ins supported by the browser and installed on the browser. systemLanguage - The language being used such as "en-us". userAgent - In my case it is "Mozilla/4.0 (compatible; MSIE 4.01; Windows 95)" which describes the browser associated user agent header. userLanguage - The languge the user is using such as "enus".

Navigator Methods
javaEnabled() - Returns a boolean telling if the browser has JavaScript enabled. taintEnabled() - Returns a boolean telling if the browser has tainting enabled. Tainting is a security protection mechanism for data.

Multiple Forms in the same Web Page


Example

How to Display HTML tags in browser


There are a few ways to get around this. You could put your markup into a textarea box. You can use an xmp tag. Or you could use '& gt;' instead of >. example

Where does Password Encryption takes place? Client side or server side

there are two popular approaches of implementing encryption


One, which is done at the client side and Two, which is done at the server side (i.e., the request carries the actual password and at the server it's encrypted to be processed further).

Pictorial Representation of password authentication scenario works

How can the encryption be implemented? Will JavaScript/VBScript suffice?

How good would Applets be?


They are normally shipped in JAR bundles which gives an extra layer of security

How good is Java Applet?


Bytecode tempering is automatically detected: if an intruder somehow gets hold of the bytecodes and changes that, the changed bytecode will throw an exception while running whereas any such changes in the JavaScript (or VBSCript) source won't be detected. Security Mechanism of Java is much more versatile: the above point is also an integral part of the Java Security mechanism, It's quite versatile and layered. No such benefit is available with JavaScript (or VBScript).

How good is Java Applet?


JVM offers a far more consistent environment: bytecodes run within a Java Virtual Machine which obviously offers a far more consistent and stable environment as compared to the environment in which JavaScript (or VBSCript) code runs. Impl of different public/private keys for every new request: you would probably be aware of the Secure Key concept which forms a part of the password on many systems. The underlying idea in such implementations is to have part of the password which keeps on changing on a continuous basis and thus making it virtually impossible for the attackers to guess that. Similarly, if we want to step up the encryption strength to an even higher level, we can put in place different public/private key combinations for every new request.

Step 1
#1: typing the Login URL of Online SBI will get you a web page which will have a JS function named encrypt() and an applet named encryptApplet. Find below the code-snippet as obtained from the Page Source of the Login page:

step2
#2: Once you enter the password and click 'Login' button, the entered password first goes through the basic checks (minimum and maximum length) and if it passes that then it is encrypted by the applet before it's sent to the web/app server. Notice that the public key id is set as it travels to the server as a hidden key which is where used for identifying the corresponding private key id for decrypting the password. This makes the web app implement a different public/private key combo for every new request.

Step 3
#3: see the change in password length before and after pressing 'Login' button which actually shows that the encryption is taking place before the request being sent to the server. Notice that the password is encrypted when the 'Login' button is clicked (it turns grey when clicked). Clicking the button first performs the basic validations, then the password encryption, and finally it submits the request to the web/app server.

Step 4
#4: see below a snapshot showing how an external JavaScript code looks like when opened in the browser versus how an applet JAR file opened in browser looks like. Evidently JavaScript code is easily visible as it's plain text. Whereas, opening up the downloaded JAR/Bytecodes will mostly have special characters and you got to try hard to get hold of the source, if at all that's possible:

Das könnte Ihnen auch gefallen