490 likes | 505 Views
Learn about client-side programming in JavaScript for interactive web pages. Compare JavaScript vs. Java in web development, scripting languages, and common tasks. Discover limitations, capabilities, and syntax of JavaScript.
E N D
Lecture 16JavaScriptE-mail (SMTP, POP) CPE 401 / 601Computer Network Systems slides are modified from Dave Hollinger
Client-side programming • HTML is good for developing static pages • in order to develop interactive/reactive pages, must integrate programming • Client-side programming • programs are written in a separate programming language • programs are embedded in the HTML of a Web page, with tags to identify the program component • e.g., <script type="text/javascript"> … </script> • the browser executes the program as it loads the page, integrating the dynamic output of the program with the static content of HTML JavaScript
JavaScript vs. Java • JavaScript is very good for simple tasks, GUI layout • flexible data typing, primitive object types fine for quick development • integration with HTML makes layout & control of GUI elements easy • not much library support, • only primitive data structuring capabilities • not well-suited to multi-file projects, OO approach JavaScript
JavaScript vs. Java (cont) • Java is better at complex tasks, especially graphics • full-featured, more robust, extensive libraries of classes/routines • can support large projects, interacting objects • GUI layout is difficult, integration with HTML not obvious • make use of the the strengths of each language • include applets in a page when needed (e.g., graphics) • allow communication between applet & JavaScript JavaScript
Scripts vs. programs • Scripting language is a simple, interpreted programming language • scripts are embedded as plain text, interpreted by application • simpler execution model: don't need compiler or development environment • saves bandwidth: source code is downloaded, not compiled executable • platform-independence: code interpreted by any script-enabled browser • but: slower than compiled code, not as powerful/ full-featured JavaScript
Scripting Languages • JavaScript: first Web scripting language, developed by Netscape in 1995 • syntactic similarities to Java/C++, but simpler & more flexible • (loose typing, dynamic variables, simple objects) • JScript: Microsoft version of JavaScript, in 1996 • same core language, but some browser-specific differences • IE & Netscape can (mostly) handle both • JavaScript 1.5 & JScript 5.0 cores conform to ECMAScript standard • VBScript: client-side scripting version of Microsoft Visual Basic JavaScript
Common scripting tasks • adding dynamic features to Web pages • validation of form data • image rollovers • time-sensitive or random page elements • handling cookies • defining programs with Web interfaces • utilize buttons, text boxes, clickable images, prompts, frames JavaScript
Limitations of client-side scripting • script code is embedded in the page • viewable to the world • for security reasons, scripts are limited in what they can do • e.g., can't access the client's hard drive • designed to run on any machine platform, • scripts do not contain platform specific commands • script languages are not full-featured • e.g., JavaScript objects are crude, not good for large project development JavaScript
JavaScript Capabilities • Add content to a web page dynamically. • Alter a web page in response to user actions. • React to user events. • Interact with frames. • Manipulate HTTP cookies JavaScript
JavaScript is not Java • JavaScript is a very simple scripting language. • Syntax is similar to a subset of Java. • Interpreted language. • Uses objects, • but doesn't really support the creation of new object types • It almost does, but it's cumbersome. JavaScript
JavaScript Variables • Untyped! • Can be declared with var keyword: var foo; • a local variable inside a function • Can be created automatically by assigning a value: foo=1; blah="Hi Mehmet"; • variable is a global variable. JavaScript
Literals • The typical bunch: • Numbers 17 123.45 • Strings "Hello Mehmet" • Boolean: true false • Arrays: [1, "Hi Mehmet", 17.234] Arrays can hold anything! JavaScript
Operators • Arithmetic, comparison, assignment, bitwise, boolean • pretty much just like C + - * / % ++ -- == != > < && || ! & | << >> JavaScript
Control Structures • Again – pretty much just like C: if if-else ?: switch for while do-while • And a few not in C for (var in object) with (object) JavaScript
Objects • Objects have attributes and methods. • Many pre-defined objects and object types. • Using objects follows the syntax of C++/Java: objectname.attributename objectname.methodname() JavaScript
Array Objects • Arrays are supported as objects. • Attribute length • Methods include: concat join pop push reverse sort var a = [8,7,6,5]; for (i=0;i<a.length;i++) a[i] += 2; b = a.reverse(); JavaScript
Pre-defined object types • String : manipulation methods • Math : trig, log, random numbers • Date : date conversions • RegExp : regular expressions • Number : limits, conversion to string JavaScript
Predefined Objects • JavaScript also includes some objects that are automatically created • always available • navigator • screen • window • document • available attributes of current document are •Title • Referrer • URL • Images • Forms • Links • Colors JavaScript
document methods document.write() • like a print statement • the output goes into the HTML document. document.write("My title is" + document.title); string concatenation! JavaScript
JavaScript Example <HEAD> <TITLE>JavaScript is Javalicious</TITLE> </HEAD> <BODY> <H3>I am a web page and here is my name:</H3> <SCRIPT> document.write(document.title); </SCRIPT> <HR> JavaScript
JavaScript and HTML Comments <SCRIPT> <!-- document.write("Hi Mehmet"); document.bgColor="BLUE"; --> </SCRIPT> HTML comment JavaScript
JavaScript Functions • The keyword function used to define a function (subroutine): function add(x,y) { return(x+y); } JavaScript
JavaScript Events • JavaScript supports an event handling system. • You can tell the browser to execute javascript commands when some event occurs. • Sometimes the resulting value of the command determines the browser action. JavaScript
Simple Event Example <BODY BGCOLOR=WHITE onUnload="restore()"> <H5>Hello - I am a very small page!</H5> <SCRIPT> savewidth = window.innerWidth; saveheight = window.innerHeight; function restore() { window.innerWidth = savewidth; window.innerHeight = saveheight; } // Change the window size to be small window.innerWidth = 300; window.innerHeight = 50; document.bgColor = 'cyan'; </SCRIPT> JavaScript
Buttons • You can associate buttons with JavaScript events • buttons in HTML forms <FORM> <INPUT TYPE=BUTTON VALUE="Don't Press Me" onClick="alert('now you are in trouble!')“ > </FORM> JavaScript
Some Events (a small sample) onUnLoad onLoad onClick onMouseUp onMouseDown onDblClick onMouseOver Window events Button events Link events JavaScript
Document Object Model • Naming hierarchy used to access individual elements of a HTML document. • Easy to use if you name all entities: • Forms, fields, images, etc. <FORM ID=myform ACTION=… > Please Enter Your Age: <INPUT TYPE=TEXT ID=age NAME=age><BR> And your weight: <INPUT TYPE=TEXT ID=weight NAME=weight><BR> </FORM> From javascript you can get at the age input field as: document.myform.age.value JavaScript
Form Field Validation • You can have JavaScript code that makes sure the user enters valid information. • When the submit button is pressed the script checks the values of all necessary fields: • You can prevent the request from happening. JavaScript
The Form function checkform() { if (document.myform.age.value == "") { alert("You need to specify an age"); return(false); } else return(true); } … <FORM METHOD=GET ACTION=foo.cgi NAME=myform onSubmit="return(checkform())"> AGE: <INPUT TYPE=TEXT NAME=Age> <INPUT TYPE=SUBMIT> </FORM> Needed to prevent the browser from submitting! JavaScript
Important: Form Validation!!! • It's a good idea to make sure the user fills out the form before submitting. • Users can bypass your form • they can create requests manually • or their own forms • Your CGI programs cannot rely (soley) on Client-Side JavaScript to validate form fields! JavaScript
Email • SMTP - Simple Mail Transfer Protocol • RFC 821 • POP - Post Office Protocol • RFC 1939 • Also: • RFC 822 Standard for the Format of ARPA Internet Text Messages • RFCs 1521, 1522 Mime Email Protocols
Terminology • User Agent: • end-user mail program • Message Transfer Agent: • responsible for communicating with remote hosts and transmitting/receiving email • both a client and server • Mail Exchanger: • host that takes care of email for a domain. Email Protocols
SMTP Used to exchange mail messages between mail servers (Message Transfer Agents) MTA MTA MTA SMTP SMTP File System UA UA Email Protocols
SMTP Protocol • SMTP sender is the client • SMTP receiver is the server. • Alternating dialogue: • client sends command and server responds with command status message. • Order of the commands is important! • Status messages include • ascii encoded numeric status code (like HTTP,FTP) and • text string. Email Protocols
SMTP Commands • HELO • identifies sender • MAIL FROM: • starts mail transaction and identifies mail originator • RCPT TO: • identifies individual recipient. • there may be multiple RCPT TO: commands. • DATA • sender ready to transmit a series of lines of text, each ends with ‘\r\n’. • A line containing only a period ‘.’ indicates the end of the data. Email Protocols
Data Format • ASCII only • must convert binary to an ASCII representation to send via email. • What if we want to send a line containing only a period? • Sender prepends a period to any line staring with a period (in the message). • Receiver strips the leading period in any line that starts with a period and has more stuff. Email Protocols
Typical Exchange > telnet mail.cse.unr.edu 25 Trying 134.197.40.1... Connected to mail.cse.unr.edu. Escape character is '^]'. 220 ponderosa.cse.unr.edu ESMTP Postfix HELO cse.unr.edu 250 ponderosa.cse.unr.edu MAIL FROM: bill@microsoft.com 250 2.1.0 Ok RCPT TO: mgunes 250 2.1.5 Ok DATA 354 End data with <CR><LF>.<CR><LF> Hi Mehmet . 250 2.0.0 Ok: queued as C0D242F8D9 Email Protocols
Leading Period DATA 354 Enter mail, end with "." on a line by itself Hi Mehmet - this message is a test of SMTP .. ..foo .. . 250 2.0.0 Ok: queued as VAA0771 Resulting Message: Hi Mehmet - this message is a test of SMTP . .foo Email Protocols
Other SMTP Commands • VRFY • confirm that a name is a valid recipient. • EXPN • expand an alias (group email address). • TURN • switch roles (sender <=> receiver). Email Protocols
Other SMTP Commands (more) • SOML • Send Or Mail • if recipient is logged in, display message on terminal, otherwise email. • SAML • Send and Mail • NOOP • send back a positive reply code. • RSET • abort current transaction. Email Protocols
Mail Headers • Email messages contain many headers • some headers are created by the UA • some are automatically added by the MTA • Every MTA adds (at least) a “Received:” header. • Some of the headers are parsed by intermediate MTAs • but the content is ignored and passed on transparently Email Protocols
POP – Post Office Protocol Used to transfer mail from a mail server to a UA Mail Server POP UA File System Email Protocols
POP (version 3) • Similar to SMTP command/reply lockstep protocol • Used to retrieve mail for a single user • requires authentication • Commands and replies are ASCII lines. • Replies start with “+OK” or “-ERR”. • Replies may contain multiple lines. Email Protocols
POP-3 Commands • USER • specify username • PASS • specify password • STAT • get mailbox status • number of messages in the mailbox. • LIST • get a list of messages and sizes • One per line, termination line contains ‘.’ only. • RETR • retrieve a message Email Protocols
More POP-3 Commands • DELE • mark a message for deletion from the mailbox • NOOP • send back positive reply • RSET • reset • All deletion marks are unmarked. • QUIT • remove marked messages and close connection Email Protocols
Optional Commands • TOP • send header lines from messages. • APOP • alternative authentication • message digest based on opening greeting sent from POP server • Requires shared secret! • No cleartext password on the network. • Does not authenticate the server!!!! Email Protocols
A Pop3 Exchange > telnet monte pop3 Trying 128.213.8.110... Connected to monte.cs.rpi.edu (128.213.8.110). Escape character is '^]'. +OK POP3 monte.cs.rpi.edu v7.59 server ready user joe +OK User name accepted, password please pass joepw +OK Mailbox open, 1 messages stat +OK 1 412 list +OK Mailbox scan listing follows 1 412 . Email Protocols
Pop3 Example Continued retr 1 +OK 412 octets Return-Path: <hollingd> Received: (from hollingd@localhost) by monte.cs.rpi.edu (8.9.3/8.9.3) id NAA06943 for joe; Mon, 20 Mar 2000 13:49:54 -0500 Date: Mon, 20 Mar 2000 13:49:54 -0500 From: Dave Hollinger <hollingd@monte.cs.rpi.edu> Message-Id: <200003201849.NAA06943@monte.cs.rpi.edu> To: joe@monte.cs.rpi.edu Status: O blah . Email Protocols