Beruflich Dokumente
Kultur Dokumente
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
JS Example
JS example in head section JS example in body section
Declaring Variables
Local Variables: variables inside a function Global Variables: Variables outside a function Example1 Example2
Comments in JS
Single Line Comment
//
HTML in JS
Example
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
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!
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.
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()">
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:
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!
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!
<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>
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 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.
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
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.
Events
onReset onSubmit
Validating checkboxes
if ( document.contact_form.terms.checked == false ) { alert ( "Please check the Terms & Conditions box." ); valid = false; }
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.
Where does Password Encryption takes place? Client side or server side
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: