COMP249 Week 3

Steve Cassidy and Yan Wang

Staff-Student Liaison

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 Browser as a Platform

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

  • JavaScript was first introduced by Netscape as a means of scripting the behaviour of their browser. It was soon copied by Microsoft (as JScript).
  • The language has now been standardised as ECMAScript and Netscape/Microsoft/Opera/etc implement versions of this language with their own extensions.
  • Javascript is able to change the behaviour of a web page by responding to user interaction with page elements.

Security and Client Side Programming

  • 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.

Security and Client Side Programming

  • 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.

  • refer to ActiveX security vs. Java security

JavaScript the Language

  • 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

Javascript Operators

  • 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 */
    }    
              
    

Example Program

// 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);
          

Example 1

 

Javascript Functions

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 2

Javascript Objects

  • Objects 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;
      

Javascript Array Object

/* 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]);

Javascript Date Object

/* 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

Javascript Date Object

  • getDate() //e.g. 10, the day in the month
  • getDay() // 0~6, the day's index in the week
  • getMonth() //0~11, the month's index
  • getYear()
  • getHours()
  • getMinutes()
  • getSeconds()
An Example (diplay the day in the week)

Object Literal Notation

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)

Object Prototypes

/* 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

Using JavaScript

  • 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">
              
    

Javascript Event Handlers

  • Initial Javascript gets called when page is read into browser.

  • Can add calls to Javascript for certain events associated with page elements:
<tag attribute1 attribute2 onEventName="javascript code;">
<!-- eg... -->
<a href="" onClick="popupFunc();">
<img src=".." onMouseOver="rollover();">
<body onLoad="initialiseSomething();">
<form onSubmit="validateForm();">
              

JavaScript and the Browser

  • 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.

Document Object Model

DOM Examples

	// 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)
	

Example

DOM Example

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

Status Bar

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"> 
      
  • How does this affect page useability?
  • Why doesn't it work in some browsers?
Example

Some Javascript Idioms

  • Javascript gets used for many tasks within web pages, look at some of the common examples:

    • Mouseover Actions
    • Form validation
    • Popup windows
    • Ajax

Image Rollovers

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'"/>
      
	  

Example

Form Validation

  • 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

Form Completed

/* 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
}
      

Source

Email Validation

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
}
      

Example

Popup Windows

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>

Example

Ajax

  • Asynchronous Javascript and XML
  • The browser requests data from the server in the background
  • The data is used to modify the content of the current page
  • Faster response times since whole pages don't need to reload
  • Basic requirement is XMLHttpRequest
  • Eg: Google Suggest
  • We'll look at this in more detail later in the semester

Notes and Resources