Scripting the Web Client Side ECMAScript Document Object
Scripting the Web Client Side ECMAScript & Document Object Model J 0 1
Java. Script History • Java was born as “Live. Script” at the beginning of the 94’s. • Name changed into Java. Script (name owned by Netscape) • Microsoft responds with Vbscript • Microsoft introduces JScript (dialect of Javascript) • A standard is defined: ECMAScript (ECMA-262, ISO -16262) J 0 2
Java. Script Myths Java. Script is NOT simple Simple tasks are indeed simple Java. Script is NOT Java J 0 3 Java. Script Browser Control Networking NO YES NO Graphics YES Partial
Java. Script is… Scripted (not compiled) Powerful Object-based Cross-Platform Client and Server J 0 4
Java. Script allows… Dynamic Web Sites Dynamic HTML (DHTML) Interactive Pages/Forms Server-Side CGI Functionality Application Development J 0 5
Java. Script can… Build Objects Use Events Enforce Security Embed or Componentize J 0 6
e r Co Base • Syntax is C-like (C++-like, Java-like) case-sensitive, statements end with (optional) semicolon ; //comment /*comment*/ operators (=, *, +, +=, !=, ==, &&, …) • Basic data types integer, floating point, strings (more later) • Loosely typed variables (Basic-like) var x=3; J 0 7
e r Co J 0 8 Statements • if (expression) {statements} else {statements} • switch (expression) { case value: statements; break; … default: statements; break; } • while (expression) {statements} • do (expression) while {statements} • for (initialize ; test ; increment) {statements}
e r Co Java. Script and HTML Between <SCRIPT> and </SCRIPT> tags Between <SERVER> and </SERVER> tags In a <SCRIPT SRC=“url”></SCRIPT> tag In an event handler: <INPUT TYPE=“button” VALUE=“Ok” on. Click=“js code”> <B on. Mouse. Over=“Jscode”>hello<B> J 0 9
e r Co a=“foo”; b=‘tball’ Useful methods: a+b => football J 0 10 Strings a<b => true a. char. At(0) => f index. Of(substring), last. Index. Of(substring) char. Code. At(n), from. Char. Code(value, …) concat(value, …), slice(start, end) to. Lower. Case(), to. Upper. Case() replace(regexp, string), search(regexp)
e r Co Strings a=“foo”; TAG-related methods: a. bold() => <B>foo</B> big(), blink(), fontcolor(), fontsize(), small(), strike(), sup() anchor(), link() J 0 11
e r Co Functions function f(x) {return x*x} _______________________ function add(x, y) {return x+y}; function multiply(x, y) {return x*y}; function operate(op, x, y) {return op(x, y)}; operate(add, 3, 2); => 5 J 0 12
e r Co J 0 13 Example <HTML> <HEAD> <SCRIPT> function fact(n) { if (n==1) return n; return n*fact(n-1); } </SCRIPT> </HEAD> …
e r Co J 0 14 Example <BODY> <H 2>Table of Factorial Numbers </H 2> <SCRIPT> for (i=1; i<10; i++) { document. write(i+"!="+fact(i)); document. write("<BR>"); } </SCRIPT> </BODY> </HTML>
e r Co Example <BODY> <SCRIPT> n=window. prompt("Give me the value of n", 3) document. write("fact("+n+")="+fact(n)); document. write("<BR>"); </SCRIPT> </BODY> </HTML> J 0 15
e r Co Object: J 0 16 Objects A data structure with methods; a special method is the “constructor”. function Rectangle(w, h) { Instance variables this. width=w; this. height=h; this. area=function(){return this. width*this. height} } method a=new Rectangle(3, 4); a. area() => 12 a. width => 3
e r Co Objects Actually, Java. Script does NOT have classes and inheritance. Moreover, the approach we have shown is not the most efficient in terms of memory allocation. It would be better to use the “prototype” feature, which can be consideres a STATIC object J 0 17 Rectangle. prototype. area=function(){return this. w*this. h}
e r Co Arrays a = new Array() a[0]=3; a[1]=“hello”; a[10]=new Rectangle(2, 2); a. length() => 11 Arrays can be SPARSE, INHOMOGENEOUS , ASSOCIATIVE a[“name”]=“Jaric” J 0 18 z=new Rectangle(3, 4); z[“width”] z. width
M O D <A NAME=…> Symbol Object hierarchy Objects means containment (has-a) Dashed line means “is an instance of” J 0 19 <A HREF=…> st e o e M t Slid h T tan or p Im
Window M O D “A web browser window or frame” Main properties J 0 20 Objects history frames[] document location navigator screen parent – top Other properties status – default. Status name
M O D Window Main methods alert(), prompt(), confirm() focus(), blur() move. By(), move. To() resize. By(), resize. To() scroll(), scroll. By(), scroll. To() set. Interval(), clear. Interval() set. Timeout(), clear. Timeout() J 0 21
M O D Screen “Information about the display” Main properties avail. Height, avail. Width height, width color. Depth, pixel. Depth hash J 0 22
M O D Navigator “Information about the browser in use” Main properties app. Name app. Version Platform Main methods java. Enabled() Other properties Info on available plugins, but only in Netscape Navigator! J 0 23
History M O D “The URL history of the browser” Main properties lenght J 0 24 Main methods back() forward() go(+/-n) go(target_substring)
M O D Location “The specification of the current URL” Main properties href protocol, hostname, port search hash J 0 25 Main methods reload() replace()
M O D Document “An HTML document” J 0 26 Main properties Main methods Arrays of Component Objects open() anchors[] close() applets[] clear() embeds[] write() Other properties forms[] bg. Color, fg. Color, link. Color, vlink. Color links[] last. Modified plugins[] title, URL, referrer, cookie
M O D Image “An image embedded in an HTML document” Main properties border [width in pixels] height width src [URL of the image to be displayed] J 0 27
M O D J 0 28 Events on. Click User clicks once. (*) Link, button on. Dbl. Click User clicks twice Document, Image, Link, button on. Mouse. Do wn User presses mouse button (*) Document, Image, Link, button on. Mouse. Up User releases mouse button (*) Document, Image, Link, button on. Mouse. Ov er Mouse moves over element Link, Image, Layer on. Mouse. Out Mouse moves off element Link, Image, Layer on. Key. Down User presses key (*) Document, Image, Link, Text elements on. Key. Up User releases key Document, Image, Link, Text elements on. Key. Press Key. Down+Key. Up (*) Document, Image, Link, Text elements (*) Return false to cancel default action
M O D on. Focus Element gains focus Text. Element, Window, all form elements on. Blur Element loses focus Text. Element, Window, all form elements on. Change User selects/deselects a text and moves focus away Select, text input elements on. Error while loading image Image on. Abort Loading interrupted Image on. Load Document or image finishes loading Window, Image on. Unload Document is unloaded Window on. Resize Window is resized Window on. Reset Form reset requested (*) Form on. Submit J 0 29 Events Form submission requested(*) Return false to cancel default action Form
M O D Properties Input form Methods blur() focus() select() click() length default. Value Objects Button X X X X X X X X Reset X X X X X Submit X X X X X Text X X X Textarea X X X Password X X X File. Uploa d X X X Checkbox X X Radio X X Select Hidden checked Properties default. Checked J 0 30 X X X X type value name options[] selected. Index X X X Event Handlers onblur onfocus onchange onclick
M O D Form “An HTML input form” Main properties action [destination URL] method [get/post] name [name of Form] name [destination Window] Elements[] [list ; of contained elements] J 0 31 Main methods reset() submit()
M O D Events <HTML> <HEAD> <TITLE>Form Example</TITLE> <SCRIPT LANGUAGE="Java. Script 1. 2"> function set. Color() { var choice; choice = document. color. Form. color. selected. Index; switch(choice) { case 0: document. bg. Color = "FF 0000"; break; case 1: document. bg. Color = "00 FF 00"; break; case 2: document. bg. Color = "0000 FF"; break; case 3: document. bg. Color = "FFFFFF"; break; case 4: document. bg. Color = "FFFF 00"; break; case 5: document. bg. Color = "FF 00 FF"; break; } J 0 32 } </SCRIPT>
M O D Events <BODY> <CENTER><H 1>Color Changer</H 1></CENTER> <BR> Select Your Favorite Background Color: <FORM NAME="color. Form"> <SELECT NAME="color" on. Change=set. Color() > <OPTION VALUE="red">Red <OPTION VALUE="green">Green <OPTION VALUE="blue">Blue <OPTION VALUE="white">White <OPTION VALUE="yellow">Yellow <OPTION VALUE="purple">Purple </SELECT> </FORM> </BODY> </HTML> J 0 33
A more complex example -1 A simple data entry validation page J 0 34
A more complex example -2 Start of file “Form. Validation. html” <HTML> <HEAD> <TITLE>Data Form Validation Example</TITLE> <SCRIPT LANGUAGE="Java. Script 1. 1" SRC="Form. Check. js"></SCRIPT> Load file “Form. Check. js”, which contains several Java. Script functions J 0 35
A more complex example -3 function is. Empty(s) { return ((s == null) || (s. length == 0)) } Check that the string “s” is not empty function warn. Empty (the. Field, s) { Issue a warning var m. Prefix = "You did not enter a value into the "; message var m. Suffix = " field. This is a required field. Please enter it now. "; the. Field. focus(); alert(m. Prefix + s + m. Suffix); return false; } All this is contained in the file “Form. Check. js” J 0 36
A more complex example -4 function prompt. Entry (s) { window. status = "Please enter a " + s; } Type a message in the status bar function validate. Personal. Info(form) Validate the form { return ( check. String(form. elements["Last. Name"], s. Last. Name) (should run over all fields ) And perform suitable checks) } function check. String (the. Field, s) { if (is. Empty(the. Field. value)) return warn. Empty (the. Field, s); else return true; } J 0 37 Check that “the. Field” is not empty All this is contained in the file “Form. Check. js”
A more complex example -5 <SCRIPT> Global variables var s. Company="Company Name"; var s. Last. Name="Last Name"; var form="Personal. Info"; J 0 38 Value-printing function display. Personal. Info(form) { var output. Table = "<HTML><HEAD><TITLE>Results</TITLE></HEAD>" + "<BODY><H 1>Data Entered: </H 1><TABLE BORDER=1>" + "<TR><TD>" + s. Last. Name + "</TD><TD>" + form. elements["Last. Name"]. value + "</TD></TR>" + "<TR><TD>" + s. Company + "</TD><TD>" + form. elements["Company"]. value + "</TD></TR></TABLE><FORM>“ + "<INPUT TYPE="BUTTON" NAME="Back" VALUE="Back" on. Click="history. back()"> </FORM></BODY></HTML>" Add a Button to go document. writeln(output. Table) back in history document. close() return true } </SCRIPT> </HEAD> End of “HEAD” portion of “Form. Validation. html”
A more complex example -6 J 0 39 <BODY BGCOLOR="#ffffff"> <CENTER><H 2>PERSONAL INFORMATION </H 2></CENTER> <P><P><I>Fields marked with an asterisk (*) must be entered. </I> <FORM NAME="Personal. Info"> <TABLE> <TR> <TD>* Family Name: </TD> <TD><INPUT TYPE="text" NAME="Last. Name" First Field on. Focus="prompt. Entry(s. Last. Name)" on. Change="check. String(this, s. Last. Name)" ></TD> </TR> <TD>Company Name: </TD> Second Field <TD><INPUT TYPE="text" NAME="Company" on. Focus="prompt. Entry(s. Company)"></TD> </TR> Start of “BODY” portion of “Form. Validation. html”
A more complex example -7 <TR> <TD> First <INPUT TYPE="BUTTON" NAME="fake. Submit" VALUE="Display" on. Click="if (validate. Personal. Info(this. form)) display. Personal. Info(this. form); "> </TD> <TD><INPUT TYPE = "reset" VALUE = "Reset"> Second Button </TD> </TR> </TABLE> <P> NOTE: We replace the usual Submit button with a "Display" that acts locally, <BR>by calling some code to display what was typed in. </FORM> </BODY> </HTML> J 0 40 End of file “Form. Validation. html” Button
M O D Applet “An applet embedded in a Web page” Properties Same as the public fields of the Java applet J 0 41 Methods Same as the public methods of the Java applet
Server-Side Java. Script Not discussed here! A substitute for CGI. Server-dependent technology to process the Web page before passing it to the client. (The Netscape SSJS object model is different from the Microsoft ASP object model, although Java. Script can be used as SSLanguage for ASP) See http: //en. wikipedia. org/wiki/Server-side_Java. Script J 0 42
Rhino is an open-source implementation of Java. Script written entirely in Java. It is typically embedded into Java applications to provide scripting to end users. http: //www. mozilla. org/rhino/ J 0 43
References Standard ECMA-262 ECMAScript Language Specification: http: //www. ecma-international. org/publications/standards/Ecma 262. htm Books: • D. Flanagan “Javascript. The definitive guide” O’Reilly. • D. Goodman “Dynamic HTML. The definitive reference” O’Reilly J 0 44
Live. Connect A two-faced technology to let Java. Script interact with Java, so that: • A Java. Script script can control and coordinate Java applets, and let Java applets interact with plugins. • A Java Applet can execute Java. Script code. J 0 45 • https: //developer. mozilla. org/en/Java. Script/Guide/Live. Connect_ Overview • http: //download. oracle. com/javase/1. 4. 2/docs/guide/plugin/develo per_guide/java_js. html
Java-Java. Script interaction: JSObject allows Java to manipulate objects that are defined in Java. Script. Values passed from Java to Java. Script are converted as follows: JSObject is converted to the original Java. Script object. Any other Java object is converted to a Java. Script wrapper, which can be used to access methods and fields of the Java object. Converting this wrapper to a string will call the to. String method on the original object, converting to a number will call the float. Value method if possible and fail otherwise. Converting to a boolean will try to call the boolean. Value method in the same way. Java arrays are wrapped with a Java. Script object that understands array. length and array[index]. A Java boolean is converted to a Java. Script boolean. Java byte, char, short, int, long, float, and double are converted to Java. Script numbers. J 0 46 Note If you call a Java method from Java. Script, this conversion happens automatically--you can pass in "int" argument and it works.
Java-Java. Script interaction: JSObject Values passed from Java. Script to Java are converted as follows: Objects that are wrappers around Java objects are unwrapped. Other objects are wrapped with a JSObject. Strings, numbers, and booleans are converted to String, Float, and Boolean objects respectively. Examples (String) window. get. Member("name") (JSObject) window. get. Member("document") J 0 47
Java-Java. Script interaction: JSObject The netscape. javascript. JSObject class has the following methods: Method Description Calls a Java. Script method Evaluates a Java. Script expression get. Member Retrieves a named member of a Java. Script object get. Slot Retrieves an indexed member of a Java. Script object remove. Member Removes a named member of a Java. Script object set. Member Sets a named member of a Java. Script object set. Slot Sets an indexed member of a Java. Script object to. String Converts a JSObject to a string The netscape. javascript. JSObject class has the following static methods: get. Window J 0 48 Gets a JSObject for the window containing the given applet
Java-Java. Script interaction: Java. Script side <HTML> <head> <script> function g(x){return x+x} function f(){return "Called f()"; } </script> </head> <body> <script type="text/Java. Script"> <!-- //hide script from old browsers document. write("<h 2>Java. Script is enabled. </h 2>") // end hiding contents from old browsers --> </script> <noscript><h 2>Java. Script is not enabled, or your browser has restricted this file from showing active content. </h 2></noscript> J 0 49
Java-Java. Script interaction: Java. Script side <script> <!-- //hide script from old browsers var j. Enabled = navigator. java. Enabled(); if (j. Enabled){ document. write("<h 2>JAVA is enabled. </h 2>") }else{ document. write("<h 2>JAVA is <i>NOT</i> enabled. </h 2>") } // end hiding contents from old browsers --> </script> J 0 50 <APPLET code="javascript. My. Applet. class" name="app" codebase="classes/" align="baseline" width="200" height="200" MAYSCRIPT> <PARAM NAME="param" VALUE="1"> If your browser is blocking the content, please click on the bar above. </APPLET>
Java-Java. Script interaction: Java. Script side J 0 51 <script language="Javascript"> document. write(f()); </script> <script language="Javascript"> document. write(app. comment); app. r=255; document. write(app. square("3"); </script> <form> <input name="Change. Color. Button" value="Change color" type="button" onclick="app. r=(app. r+100)%256; app. repaint()"; /> </form> <input title="write. Button" value="write on console" type="button" onclick='java. lang. System. out. println("a java message"); '; /> </form> </body> </html>
Java-Java. Script interaction: applet side package javascript; import netscape. javascript. *; import java. applet. *; import java. awt. *; public class My. Applet extends Applet { private JSObject main. Window; private JSObject page. Doc; private JSObject location; J 0 52 private String s; public String comment="instance. Var. Content"; public void init() { System. out. println("initing"); main. Window = JSObject. get. Window(this); page. Doc = (JSObject) main. Window. get. Member("document"); location = (JSObject) main. Window. get. Member("location"); s = (String) location. get. Member("href"); // document. location. href }
Java-Java. Script interaction: applet side public int r=0; public int g=255; public int b=0; public void start(){ s=(String)main. Window. call("f", null); String[] string. Args = new String[1]; string. Args[0] = "5"; s=(String)main. Window. call("g", string. Args); System. out. println (" Calling g returned "+s); } J 0 53 public void paint(Graphics gra) { if (s==null) s="NULL"; gra. set. Color(new Color(r, g, b)); Dimension d=this. get. Size(); gra. fill. Rect(0, 0, d. width, d. height); gra. set. Color(new Color(0, 0, 0)); gra. draw. String("VERSION 1", 80); gra. draw. String(s, 30); }
Java-Java. Script interaction: applet side void change. Color(String s) { int x=Integer. parse. Int(s); r=x; this. repaint(); } public String square(String sx) { int x=Integer. parse. Int(sx); return new Integer(x*x). to. String(); } } J 0 54
- Slides: 54