We need a representative from COMP249 for the staff-student liaison committee. Will meet for the first time in week 3, March 12, Wednesday 1-2pm.
The idea of a platform is something we can deliver applications on; traditionally this has been Windows, MacOS, Unix etc. Since the browser became more capable, we've regarded it as a new platform that we can write applications for. The work can go on at the server end or more recently at the client (browser) end. The technologies used are HTML and CSS for presentation and Javascript to define behaviour or do work.
Javascript is able to change the behaviour of a web page by responding to user interaction with page elements.
Security is a major issue when you allow unknown and untrusted agents to run programs on your computer.
There are two general approaches to dealing with this issue:
Restrict the things that the client side programs are allowed to do.
Implement some kind of validation and verification of the source of programs.
JavaScript takes the first approach, you can't, for example, read and write local files from JavaScript.
Other client side languages provide a restricted subset of the full language to untrusted programs. Eg. Java and Safe Tcl.
ActiveX takes the second approach. An ActiveX program can do anything but is signed and encrypted to help ensure that it comes from someone you trust.
Note that writing to local disk isn't the only security risk. Others include capturing and sending data to remote sites and denial of service.
JavaScript is another scripting language not unlike Perl, Tcl and Python.
Has the usual control structures etc.
JavaScript variables can hold:
Numbers: integer and floating point
Booleans: true, false
Strings: "Hello World!"
Objects: myObj = new Object();
Null: empty, no value
Undefined: value is not defined
The usual range of comparison and arithmetic operators.
String concatenation with +: "Age:" + "20" gives "Age: 20"
C style conditional operators:
preferredPet = (cats > dogs) ? "felines" : "canines"
typeof operator:
if (typeof foo = "numeric") {
/* do something */
}
// Script by http://www.mimanet.com/scripts/
theDate= new Date();
var months = new Array('January','February',
'March','April','May','June','July','August',
'September','October','November','December');
var day = theDate.getDate();
var textdate = 0;
if (theDate.getYear() < 2000)
textdate = 1900;
textdate = months[theDate.getMonth()] + ' ' + day + ', '
+ (theDate.getYear() + textdate);
document.write(textdate);
Functions can be defined to extend the language:
function raiseP(x,y) {
total=1;
for (j=0; j<y; j++) {
total*=x;
}
return total; //result of x raised to y power
}
z = 10 + raiseP(10,20);
Example 2Objects are containers in Javascript
Can have properties (member variables) and methods
Some predefined
User can define new object types
/* define an instance directly */
myPetDog=new Object();
myPetDog.name="Barney";
myPetDog.breed="beagle";
myPetDog.year=1981;
/* define an array */ myArray=new Array(3); myArray[0]="element1"; myArray[1]="element2"; myArray[2]="element3"; document.write(myArray[0]);
/* define an array */
myArray=new Array{"element1", "element2", "element3}";
document.write(myArray[0]);
/* define a date object */ var myDate=new Date(); myDate.setFullYear(2010,0,14); // set to 14th January, 2010
/* define a date object */ var myDate=new Date(); myDate.setDate(myDate.getDate()+5); // set a Date object to be 5 days into the future
An alternate notation:
myPetDog = {
name: "Barney",
breed: "beagle",
year: 1981
display: function(){
document.write("<p>A ", this.breed, " dog called ", this.name,
" born in ", this.year, "</p>" )}
}
(Can also do inheritence, etc)
/* define a prototype dog */
function display_dog() {
document.write("<p>A ", this.breed, " dog called ", this.name,
" born in ", this.year, "</p>" )
}
function petDog(name, breed, year) {
/* 'this' is a special name for the object created by 'new'*/
this.name = name;
this.breed = breed;
this.year = year;
this.display = display_dog; /* a method */
}
/* generate two instances */
myPetDog=new petDog("barney","beagle",1981);
yourPetDog=new petDog("max","terrier",1990);
/* and display them */
myPetDog.display()
yourPetDog.display()
example JavaScript code is embedded in web page headers within <script></script> tags.
Either embed the script directly (note the use of HTML and Javascript comments):
<head>
<title> ...</title>
<script language="Javascript">
<!--
// your script goes here
//-->
</script>
</head>
Or refer to an external script file:
<script language="Javascript" src="sample.js">
Initial Javascript gets called when page is read into browser.
<tag attribute1 attribute2 onEventName="javascript code;">
<!-- eg... -->
<a href="" onClick="popupFunc();">
<img src=".." onMouseOver="rollover();">
<body onLoad="initialiseSomething();">
<form onSubmit="validateForm();">
The most important data structure available to you JavaScript program is the browser and it's model of the current HTML page.
These are represented in JavaScript as objects and you can query them and in many cases modify them in your scripts.
The HTML page is modelled via the Document Object Model. In the newer browsers (IE 5, NS 6) this is very similar to the XML DOM.
Scripts also have access to CSS properties of the document elements.
// get the first table in the document
table = document.getElementsByTagName("table").item(0)
// get the first td in the second tr
row = table.getElementsByTagName("tr").item(2)
cell = row.getElementsByTagName("td").item(0)
// get the contents of the cell
txt = cell.childNodes.item(0).nodeValue
document.write(txt)
var anchorTags = document.getElementsByTagName("a");
for (var i = 0; i < anchorTags.length ; i++)
{
alert("Href of " + i + "-th element is : "
+ anchorTags[i].href + "\n");
}
Example The message shown on the status bar can be modified via the window.status property.
<a href="newstuf.html"
onMouseOver="(window.status='Click Here for New Stuff'); return true">
Javascript gets used for many tasks within web pages, look at some of the common examples:
Image rollovers work by changing the src attribute in an img tag when the mouse moves over it.
<img name='stevepicture'
src="steve.jpg"
onMouseOver="document.stevepicture.src='steve2.jpg'"
onMouseOut="document.stevepicture.src='steve.jpg'"/>
While we can validate form data on the server, the user would get a quicker response if we did some work on the client side.
Simple checks like incomplete submission and even email validation can be carried out in Javascript.
Javascript can also access and create cookies
/* Test whether the form with name="FormName" is complete */
function IsFormComplete(FormName)
{
var x = 0
var FormOk = true
while ((x < document.forms[FormName].elements.length) && (FormOk))
{
if (document.forms[FormName].elements[x].value == '')
{
alert('Please enter the '
+ document.forms[FormName].elements[x].name
+ ' and try again.')
document.forms[FormName].elements[x].focus()
FormOk = false
}
x ++
}
return FormOk
}
function IsEmailValid(FormName,ElemName)
{
var EmailOk = true
var Temp = document.forms[FormName].elements[ElemName]
var AtSym = Temp.value.indexOf('@')
var Period = Temp.value.lastIndexOf('.')
var Space = Temp.value.indexOf(' ')
var Length = Temp.value.length - 1 // Array is from 0 to length-1
if ((AtSym < 1) || // '@' cannot be in first position
(Period <= AtSym+1) || // Must be atleast one valid char btwn '@' and '.'
(Period == Length ) || // Must be atleast one valid char after '.'
(Space != -1)) // No empty spaces permitted
{
EmailOk = false
alert('Please enter a valid e-mail address!')
Temp.focus()
}
return EmailOk
}
Javascript can create popup windows which are often used for help and even more often for advertising.
<script language="JavaScript">
function mypopup() {
win = window.open("", "mywindow", "height=100,width=100")
win.location = "http://www.ics.mq.edu.au/"
}
</script>
...
<a href="#" onClick="mypopup()">Click Here!!!</a>
Netscape Javascript Documentation describes the Netscape implementation.
Microsoft's JScript Reference describes the implementation in IE.
The JavaScript entry on dmoz.org contains a number of good pointers to tutorial and reference sites.
An example of how Javascript can lead to security problems is shown in this description of the HotMail JavaScript-in-attachment attack.