CPS616 JavaScript 1997 CPS 616 January-April 1997 Computational Science Track on Base Technologies for the Information Age: Module on JavaScript See: http://www.npac.syr.edu/users/gcf/cps616javascript97 Instructor: Geoffrey Fox teamed with Meryem Ispirli, Nancy McCracken, Tom Scavo, John Yip Syracuse University 111 College Place Syracuse New York 13244-4100 Abstract of CPS616 JavaScript Presentatation Java versus JavaScript versus HTML Issues Some Simple Motivating Examples Language Features and Syntax The Peculiar Object Model -- Functions Properties and Methods Arrays in old and new JavaScript Arguments of Functions with and other object related syntax The JavaScript built in Math String and Date Objects The Navigator Objects -- Frames Windows Document Form Event Handling including Function object Cookies User Objects and Examples including using JavaScript for frames General Remarks on JavaScript - I Historically JavaScript was called LiveScript and developed by Netscape with some of the same goals as Java but focussed on a "smaller world" -- manipulation of text and options connected with Netscape Clients TEXT ............................................. COMPUTER Language HTML --> JavaScript Java <--- C++ Now we can use it under some circumstances as an alternative to Java where the "rapid prototyping" of a fully scripted language is helpful We expect somebody to develop a fully interpreted Java -- equivalently to extend JavaScript to support more built-in objects (e.g. networking, images) JavaScript is "either" active text (HTML) or a focused language! JavaScript can be thought of as Java with the AWT (Abstract Windowing Toolkit) replaced by Netscape Client JavaScript is a domain specific Interpreter for "Web Document Domain" e.g. Postscript is a domain specific Interpreter for text layout and MATLAB is an interpreter for matrix manipulation, Mathematica is domain specific for mathematics ...... General Remarks on JavaScript - II JavaScript particularly useful for multi-frame windows and for manipulating forms without complex CGI (Server Side) scripts Here it can be much faster as purely client side whereas a CGI based form has inevitable delays as requires server-client communication and invocation of a new process on server side. Java shares this advantage This client side processing speed can be essential in some applications as users would not accept long delays (several seconds) on "trivial" mouse clicks Java is a broad industry standard with a careful well documented design JavaScript comes from Netscape but is supported by Microsoft. It has a poorly documented (and thought through ?) basic design Java / Interpreter Structure Typical Java Applet Structure Java Source ---> javac compiler --> JavaVM Universal machine code in .class file Store JavaVM .class files on Web Server Download JavaVM from Server to Client. Interpreter built into browser, reads JavaVM and executes on client Typical JavaScript Structure JavaScript source is included in HTML text Combined JavaScript and HTML is downloaded and interpreted by browser on client to produce HTML page Particular user actions on HTML page (e.g. mouse clicks and form entries) can invoke JavaScript functions on the client As browser one must "understand" raw high level language, this is substantially slower than interpreting JavaVM where "just" need to map universal machine code into machine code for a particular computer Note in each case , Java and JavaScript use "runtime" which is "compiled high performance library" (probably written in C and C++) Some Performance Comments Execute C code Instruction -- 1 clock cycle ( 10^8 per second) Run a client side C subroutine -- can do upto 10^6 instructions in time (few milliseconds) that is significant for user JavaVM Interpreter -- roughly 50 times slower than C JavaVM Just in Time Compiler (effectively compile JavaVM in real time) -- roughly 2 to 8 times slower than C Native Java Compiler -- same speed as C Perl Interpreter (but does process whole program before interpreting) -- 500 times slower than C except in runtime Tcl, JavaScript "true" Interpreters - 5000 times slower than C Can still do 100-1000 instructions in time that users don't notice! Contact Host via CGI script -- Server, Network and Client HTML page regeneration delay can be measured in seconds. We need to know HTML! Note like most interpreters (look at Basic manual) JavaScript has a huge and growing number of "basic" methods and objects To study JavaScript, we will have to use some relatively advanced HTML features including Frames Forms -- especially event handlers Cookies Hello World Example of JavaScript- I A Test of JavaScript Continue with conventional HTML Hello World Example of JavaScript- II There is only one real JavaScript statement here -- namely document.writeln("textstring"); This outputs into current page the text in quotes followed by a newline And note the rather peculiar way we "hide" JavaScript from browsers that can't understand it by enclosing in convential HTML Comment syntax Note depending on your needs, JavaScript can be in Header or Body section of document Example of Clicking on a Form - I Javascript with Forms
Enter An Expression:
Result:
Example of Clicking on a Form - II Enter An Expression: 9+5 Result: 14 confirm is a native Javascript method popping up a window, requesting confirmation of requested action alert is a native Javascript method popping up a window with a message requiring user to place OK to get rid of. onclick="Javascript Statement Block" naturally executes statement(s) when button clicked Example of Parameterized HTML Javascript for Parameterizing HTML ......Bunch of Normal Stuff .... Yet More Normal Stuff Note single quotes used for JavaScript, Double quotes for HTML -- can use \' if necessary to hide special meaning from JavaScript LiveWire -- Netscape's Approach to CGI Netscape Servers now support the "LiveWire" Extension which allows you to write "CGI Programs" in JavaScript Refinements in the The included file must have .js suffix and server must be set up with correct MIME types to download .js files JavaScript URL's One can demonstrate JavaScript as an interpreter by typing JavaScript: into location text bar of your browser. This gives a two frame window where you can directly type JavaScript and see response One can use a similar capability in HREF and other atrribute definitions Go Back One Step This loads the last page visited in being clicked Using history.go(0) would reload current page The JavaScript Manual describes some interesting Image Map Examples including: JavaScript Entities in HTML One can parameterize HTML using document.write(ln) commands such as: document.writeln("string1" + JSvariable +"string2"); // etc. A "lighter weight way of achieving this can be illustrated by direct HTML syntax with NO setTimeOut Example -- Display Current Time - II The previous JavaScript goes in header of document whose body is:
Note
only used for output using document.clock.face.value onload function called when page is loaded and this starts timer. More on Document Objects -- Image The document object has several important subobjects including Anchor, Applet, Area, Form, Image and Link. It also has arrays anchors, applets, forms, images and links arrays holding all the occurrences of these objects in a particular document. We have illustrated Form and Link already -- here we look at Image in an HTML file generates an object document.fred of type Image with property document.fred.src="jim.gif" One can preload images using syntax like: image1 = new Image(); image1.src = "henry.jpg"; and then change Image in document using document.fred.src = image1.src; henry.jpg is fetched from cache and so this is fast! This technology can be used for animated images and also to quickly change a picture displayed in perhaps an online shop catalog where user chooses a new item in a form. The Asynchronous JavaScript/Browser There are several Issues that are a bit tricky due to asynchronous (thread based!) processing in Browsers This is seen in reloading JavaScript pages. This produces unclear results as different frames and associated JavaScript variables are set in adifferent order from that in which multi-frame system was built! Often get "false" errors as variables not set "in time" Note that when you set location field in a window, with a JavaScript command such as: window.location = "newurl"; Then following commands are executed immediately and do not wait wait for new page to be loaded! prototype Property This allows you to dynamically change object definitions We used function(constructor) function car(make,model) { // An Example this.make = make; this.color = 'red'; this.model = model; } mycar = new car("Ford","Explorer"); Suppose we wanted to add a new property 4wheelstatus car.prototype.4wheelstatus = false; mycar.4wheelstatus = true; We can add methods with function repaint(newcolor) { this.color = newcolor; } car.prototype.repaint =repaint; We can avoid repainting mycar by assigning mycar.repaint = specialrepaint; function specialrepaint(newcolor) {} Cookies - "hidden" alternative Cookies were introduced by Netscape to preserve client side state If you have a CGI script that services several clients (ordering T Shirts perhaps), it is neatest to use client and not server to store information such as name of user, passwords etc. Traditionally used as passed in forms using "hidden" fields set by formname.user.value = WHATHAVEYOU; Such hidden fields are passed to CGI scripts in same fashion as other variables set in form text fields hidden values can either by set by JavaScript on client side or returned built into a page constructed by CGI script which might read N values and return a new form with M new fields for user and N old entries preserved in hidden fields So hidden variables are nice but only preserved as long as you keep to page you started with or that returned by CGI script. Cookies -- Client Side Files Cookies provide an alternative mechanism where information is saved in special file on client (called cookies or cookies.txt) Note History Cache Bookmarks are also saved client side Such files can preserve information in a more robust way than hidden alternative! Cookies are supported by Microsoft and and Netscape and can be used (like forms) for pure client-side or client-server activities Neither hidden or cookies are very secure Cookies have 5 attributes -- name, expires, domain, path and secure and are specified by a single line that must specify a value for name but where all other attributes are optional. Specification of a cookie - I name=value; EXPIRES=datevalue; DOMAIN=domainname; PATH=pathname; SECURE name is required and tells you name of cookie EXPIRES is optional but if present specifies a date afterwhich cookie is to be deleted EXPIRES uses a modification of syntax returned by JavaScript function Dateobject.toGMTString(timevalueinseconds) dayofweek, Day-Month-Year Hour:Min:Secs GMT e.g. Wednesday 19-02-97 19:10:24 GMT It appears that one can just use the slightly different syntax of toGMTString so now = new DATE(); now.setTime( now.getTime() + 24*60*60); now.toGMTString() will give an expiration date of one day from now! Specification of a cookie - II DOMAIN defaults to domain of server where cookie set and general matching matching is done starting at end of domain DOMAIN=npac.syr.edu matches all servers ending with these characters PATH=/ is most general path and matches all paths but default is again path of document that set cookie. Thus you must set PATH explicitly to / if you want cookie to be valid for a file stored in directory below that of setting document SECURE if present requires a secure communication channel Use of Cookies in Server Program The Brower passes to server any cookies that are valid for a given page in HTTP header Note only name=value is passed because PATH DOMAIN SECURE and EXPIRES are used to check if cookie should be passed The server stores cookie strings in $HTTP_COOKIE environment variable as name1=value1; name2=value2; It is easy for CGI script to decode this $HTTP_COOKIE environment variable One can send cookies back to client using Set-cookie: name1=value1; expires= .. ; domain= ...; etc. before the content-type: text/html header line Use of Cookies in Client Program JavaScript string document.cookie holds cookies that are valid for this document and can be used to either set or retrieve cookie values In example, we have a page with a form that sets values and stores for a certain length of time. This is entirely processed client-side with JavaScript interpreting form and storing values in appropriate cookie entries These cookies are read on other pages (consistent with PATH and DOMAIN) and if present used to define JavaScript variables that are used in "parameterized HTML" Note document.cookie is set to a single cookie value but when read gives all cookies for this document! TAINTING! Security in JavaScript Tainting ensures that certain properties cannot be freely used These "taintable" properties include cookie, links, title etc in document; most interesting properties of forms; history; location Once you access such a property from a SERVER different from that which spawned JavaScript page, then your current statement and everything derived from it is "tainted" Note testing to see if a variable is tainted, taints your program and so one cannot write useful JavaScript programs involving tainted quantities and networking tainted variables may NOT be passed over the Network to other servers e.g. to a CGI Script You can control the tainting of pages and untaint them so that remote servers can freely use However I don't think anybody does this ...... LiveConnect Java to JavaScript - I LiveConnect is an important but still experimental capability that allows Java Applets to freely access JavaScript variables and vice versa You can use this to call java methods in JavaScript noting that a java package X is called Packages.X in JavaScript var myjavadate= new Packages.java.util.date(); // Creates a JavaScript variable from the java Date constructor This development potentially gives us an Interpreted version of Java! LiveConnect is only supported by Netscape at present You can also change java variables in running applets as long as they are public (see next page) LiveConnect Java to JavaScript - II So if Applet HelloWorld has: public void setString(String aString) { javaslocalcopy = aString; repaint(); } Then you can change javaslocalcopy from JavaScript using document.applet["HelloWorld"].setString(text stuff from JavaScript); Care must be taken in typing and best is to convert everything explicitly to Strings in Java and JavaScript Netscape needs to clarify this! Correspondingly Java Applets can control Web Pages with JavaScript functions in them and so access capabilities of Netscape Browser explicitly see NPAC TANGO System Use of Dynamic Forms (Layout) in JavaScript ... This can give a form created by JavaScript
The flexbuttons dynamic form in JavaScript function flexbuttons(maxradio, groupname, number, indname, indexselected, onprocess) /* Output a group of single selection radio or select buttons */ /* maxradio defines strategy -- if more than maxradio items use a select field, if smaller than this use radio buttons */ /* User responsible for
container and any formatting */ /* onprocess is textstring of "onclick/change" function" */ /* number is number of buttons with name indname[1...number] */ /* groupname is name of group */ /* indexselected running from 1 to number is initial selection */ Create RadioButtons Dynamically function flexbuttons(maxradio, groupname, number, indname, indexselected, onprocess) { if( number <= maxradio) { for( var i=1; i <= number ; i++) { top.fred.document.writeln(''); } // end for loop } // end radio button if statement Create Select Field Dynamically else { // Case when enough options for a select field top.fred.document.writeln(''); } // End else for generating select field } // End of flexbuttons