Domino Designer 8: JavaScript
Version 1.1
Copyright Information ©2008 wareSource.com Part #DDJS8-1.1, updated for Dom...
65 downloads
792 Views
799KB Size
Report
This content was uploaded by our users and we assume good faith they have the permission to share this book. If you own the copyright to this book and it is wrongfully on our website, we offer a simple DMCA procedure to remove your content from our site. Start by pressing the button below!
Report copyright / DMCA form
Domino Designer 8: JavaScript
Version 1.1
Copyright Information ©2008 wareSource.com Part #DDJS8-1.1, updated for Domino and Domino Designer 8.0.1. Under the copyright laws, this book may not be photocopied, reproduced, translated, or reduced to any electronic medium or machine-readable form, in whole or in part, without the prior written consent of wareSource.com. While every reasonable precaution has been taken in the preparation of this book, the author assumes no responsibility for errors or omissions, nor for the uses made of the material contained herein and the decisions based on such use. No warrantees are made, express or implied, with regard to either the contents of this work, its merchantability, or fitness for a particular purpose. The author shall not be liable for direct, indirect, special, incidental, or consequential damages arising out of the use or inability to use the contents of this book. In no event shall the author be liable for any damages whatsoever (including without limitation, damages for loss of business profits, business interruption, loss of business information, or any other loss) arising out the use of or inability to use this material, even if the author has been advised of the possibility of such damages. Lotus, Domino, Domino Designer, ScreenCam, LotusScript, Notes/FX, Lotus Notes, Notes, iNotes, DataLens, Notes Minder, and Sametime are trademarks or registered trademarks Lotus Development Corporation and/or IBM Corporation. IBM, OS/2, AS/400, S/390, AIX, DB2, and WebSphere are registered trademarks of International Business Machines, Incorporated. Windows is a trademark of Microsoft Corporation. Microsoft is a registered trademark and Windows, Internet Explorer, and ActiveX are trademarks of Microsoft Corporation. Java and JavaScript are trademarks of Sun Microsystems, Inc. All other marks are the property of their respective owners.
2
Domino Designer 8: JavaScript
Table of Contents Topic 1: Browser Objects and JavaScript................................................................9 Topic 2: Coding JavaScript in Domino Designer ..................................................25 Topic 3: Basic Language Elements........................................................................55 Topic 4: Branching and Looping Structures..........................................................71 Topic 5: Custom Functions....................................................................................83 Topic 6: JavaScript Objects ...................................................................................93 Topic 7: Arrays ....................................................................................................123 Topic 8: Browser Object Model ..........................................................................143 Topic 9: Browser Event Handlers........................................................................165 Topic 10: Field Access.........................................................................................181 Topic 11: Field Input Translation and Validation................................................203 Topic 12: Form Validation...................................................................................223 Topic 13: Window Object....................................................................................239 Topic 14: Frame Object .......................................................................................263 Topic 15: Location Object ...................................................................................273 Topic 16: Browser State Persistence....................................................................297 Topic 17: Dynamic HTML ..................................................................................321 Topic 18: JavaScript and Java Applets ................................................................341 Topic 19: Domino Views.....................................................................................365 Topic 20: JavaScript and ActiveX Controls ........................................................375 Topic 21: Asynchronous JavaScript and XML....................................................383 Topic 22: Browser Compatibility ........................................................................399 Topic 23: JavaScript Resources ...........................................................................417 Index ....................................................................................................................425
Domino Designer 8: JavaScript
3
Description During this course you will use Domino Designer 8 to add JavaScript to Domino applications that are accessed by browsers. The course covers the basic language elements of JavaScript, how to add scripts using Domino Designer, and how to exploit the various browser and language object event handlers. There is a strong emphasis on the browser object model and how it relates to the Domino object model. The course also touches on how to incorporate Dynamic HTML, Java Applets, LiveConnect, ActiveX controls, and AJAX into web-based applications.
Course goals This course will: •
build a fundamental knowledge of JavaScript as it is applied in Domino applications used by modern browsers
•
provide practical programming and debugging experience to ensure a foundation of JavaScript skills
•
understand the relationship between JavaScript and Domino data types
•
clarify the use of the various object models, including the Domino Object Model, the original browser Document Object Model, JavaScript language objects, and the newer W3C Level 1 Document Object Model
•
use JavaScript to code the Field, Button, and Form event handlers
•
build a practical understanding of data validation and error trapping
•
use DHTML to create interactive web pages
•
control Java applets using LiveConnect
•
remotely access Domino objects via CORBA
•
script ActiveX objects
•
use AJAX to request and process Domino-generated XML
•
develop practical ways to detect which browser is being used and how to code appropriately.
4
Domino Designer 8: JavaScript
Audience This course assumes that you have: •
thorough knowledge of the Domino Designer 8 development environment, including Form, Page, View, Frameset, and Agent design, as well as how to set properties and set the ACL
•
knowledge of web technologies, including servers, browsers, HTML, Cascading Style Sheets, and some basic JavaScript (or other browser scripting language) and awareness of browser object properties and methods
•
basic understanding of LotusScript and the various Notes product objects
•
because this course does not review any aspects of the non-JavaScript aspects of developing applications with Domino Designer, mastery of the topics covered in these courses: •
Lotus Domino Designer 8: Basic Notes Applications
•
Lotus Domino Designer 8: Basic Browser Applications courses.
This course is part of a series of Domino Designer 8 training courses. Follow these paths to master all aspects of developing applications using Domino Designer: Clients
Notes 8 Experience
Lotus Notes 8 User Essentials NCUE8 - 1 day
Basic Notes Applications DDBNA8 - 4 days
Special Notes Features DDSNF8 - 2 days
Basic Browser Applications DDBBA8 - 1 day
DB2 for Domino 8 Administrators and Developers DB2D8 - 2 days
Languages
Formula Language DDFL8 - 2 days
LotusScript DDLS8 - 4 days
JavaScript DDJS8 - 3 days Web Agents and Web Services DDWAWS8 - 2 days
Domino Designer 8: JavaScript
5
Domino Designer 8: Basic Notes Applications provides the base knowledge for this additional training: Client Track •
Configure Domino to use DB2 as a database engine and build applications that access relational data, DB2 for Domino 8 Administrators and Developers.
•
Specialize in programming Notes applications to respond to built-in user interface features, Domino Designer 8: Special Notes Features.
•
Convert an application written for Notes clients to be used in browsers, Domino Designer 8: Basic Browser Applications.
•
Provide data to cutting-edge web applications, Domino Designer 8: Web Agents and Web Services.
Language Track. These languages apply to both Notes and browser clients: •
Learn sophisticated application techniques that fully exploit the formula language in Domino Designer 8: Formula Language.
•
Develop sophisticated applications and Agents with LotusScript in Domino Designer 8: LotusScript.
•
Add powerful client-side scripting to browser applications in Domino Designer 8: JavaScript.
Course design The course takes a task-oriented approach, during which you will work with JavaScript code that will have immediate application to your Domino applications. Because this course instructs you how JavaScript works with respect to Domino, you will be able to leverage the many JavaScript resources available to you as a developer.
6
Domino Designer 8: JavaScript
Data files To ready your computer and the Domino Server for the course, you must run the INSTALL.EXE program from the class diskette on the computer running Domino Designer. Specify the default Notes \Data directory during the installation; if you put it into a subdirectory outside the \Data directory, the examples will fail. By default, a subdirectory named \Data\DDJS8 is created for you. The DDJS8 Demo (DDJS8DEMO.NSF) database is installed. It is used to demonstrate all the code used in the course and as the starting point for the exercises. During the first exercise you will create your own non-replica copy of the DDJS8 Demo database on the Domino Server, where you will complete the exercises. There are also a number of other resource files that will be installed to your local drive (sample ActiveX controls and Java Applets) that you will use during the course. All exercises must be performed from your copy of the database running on the Domino Server and tested from there. You should have Domino Designer 8 and Internet Explorer 7+ installed on your computer (IE will run all the example code). You should also install Mozilla Firefox 2+ to test cross-browser compatibility. Be sure you have access to Domino Designer 8 Help, which should be full text indexed. Please consult the Set Up document for this course to make sure the correct environment is in place before starting the course.
Conventions This course follows these font conventions: •
Italic - database, view, form, document, macro, and field names, as well as object event handlers
•
Bold - menu options, command button names, and accelerator keys, function/statement names (for clarity)
•
Courier- user input, sample values, code examples, constants
•
Helvetica - HTML and JavaScript code examples
•
© - shows when script lines wrap in the text but should be one continuous line in the Programming Pane.
•
'' is two single apostrophes together, not a double quote mark. Domino Designer 8: JavaScript
7
Notes
8
Domino Designer 8: JavaScript
Topic 1: Browser Objects and JavaScript Key points This Topic provides a historical and conceptual background of how JavaScript relates to and interacts with browsers. It also describes how Domino Server dynamically and securely serves pages containing JavaScript to browsers.
Preview of the Domino/browser exchange This diagram illustrates the exchange between Domino and a browser (you will learn more about all the pieces in the following sections): Domino Server
File System
NSF
Web Server
HTTP Browser
This table describes the exchange between Domino and a browser: Stage 1
Description A browser requests a URL that is on the Domino server. In this example, the URL opens a Form in which the user will add values to several fields and will save the results back as a document in the NSF on the server. Pretty simple stuff.
2
Domino pulls the necessary resources from the NSF, in this example, a Form.
Topic 1: Browser Objects and JavaScript
9
Stage 3
Description The Form itself is designed in Domino Designer and Domino is responsible for converting various design elements into HTML: • Fields are converted to HTML tags. • The Save button that is designed to run @Command([FileSave]); @Command([FileCloseWindow]) is
converted to JavaScript that submits the document back to the server when clicked. • The Form may also have text that has embedded HTML tags (including inline <SCRIPT> tags) and has been marked as Passthru HTML, so Domino doesn’t need to do any conversion. • The Form may have “passthru” elements, where code was added in Domino Designer in various browser-specific places, such as: • HTML Head Content. Added to the HTML page tag (uses the Function language to dynamically define content). • JS Header. JavaScript added to a <SCRIPT> block in the page . • OnLoad. JavaScript added to the tag onLoad event handler. • If the Form calls an Agent in its WebQueryOpen event, the code (written in LotusScript or Java) is executed (often used to programmatically set default field values). After all the computations are performed (regardless of the original incarnation of any element), the Form is converted entirely to browser-compatible HTML and sent down to the browser via HTTP.
10
Topic 1: Browser Objects and JavaScript
Stage 4
Description The browser renders the elements of the HTML page. In this example, the Form has an tag pointing to a .JPG in the \HTML directory on the Domino server, so as the browser renders the page, it fetches the image. You can think of the page as having a visual aspect, what the user sees, and code. Some of the code was run before the visual pieces were rendered (like the code in the onLoad event), but other client-side code isn’t executed until the user takes some action, like clicking a button. The point to be made here is that all “stuff” of the visual aspects and client-side code buried in the HTML page has been shipped down to the browser from Domino, and it is now up to the browser to deal with it. What this means for the developer is that you must deeply understand at least these two things: • How Domino converts (or passes through) things you add in Domino Designer. • What the browser does with page once it arrives (including whether or not the browser is capable of processing the page).
5
In this example, the user clicks the Save button and the page is submitted back to Domino. With respect to the Save button, as the Form developer you not only had to add all the things necessary for the page to render and operate properly in the browser, you also had to anticipate what happens when the user is done with the page. In this case you added an image of a Save button that when clicked submits the Form back to the server. A Form may also have a Cancel button, or a Go Back to the View button; a View may have a Next Page button to show the next 20 documents in the View, or a New Document button. So now because you also have to anticipate user navigation away from the page, you now have three things about the Form you must worry about.
Topic 1: Browser Objects and JavaScript
11
Stage 6
Description Domino receives the page from the browser and is now responsible for transforming its information into a document in the database. To do this, Domino fetches the original Form to interpret the field data. It runs the field formulas (computed, input translation, input validation). If there are input validation failures, Domino sends an error page back to the browser. If the Form calls an Agent in its WebQuerySave event, the code (written in LotusScript or Java) is executed (often used to more gracefully handle field validation errors or to redirect the user to another place in the application after successfully writing the document to the database).
7
Once all the conditions and code of the original Form have been met, the document is created in the database.
8
Depending on what you code to happen next, Domino can return something back to the browser, like an error or confirmation message, back to the Form for error correction, or to the next logical place in the application.
Programming challenge Programming Domino applications for browsers is really quite a challenge. As you saw above, there are several opportunities to apply code: •
Server-side code that runs before the HTML page is shipped down to the browser.
•
Client-side code that runs entirely in the browser and eventually is responsible for posting something (usually the HTML form) back to the server.
•
Server-side code that processes the response from the browser.
12
Topic 1: Browser Objects and JavaScript
In this course, the emphasis is on the client-side code, specifically how JavaScript can be used to manipulate browser and Document Object Model (DOM) objects created by tags included in the current HTML page and by JavaScript language itself: Browser Object Model
+
(DOM Level 0)
Browser
Client-side Scripting Document Object Model (DOM Level 1)
Domino Server
HTML
Server-side Scripting
+
+
Cascading Style Sheets
Domino Object Model
This course also necessarily must also deal somewhat with Domino as the Web Server, so you also will work with the Domino Object Model and how to use: •
@Functions to create Views as well as to code buttons and Action buttons using a subset of @Functions (the code is automatically converted to JavaScript by Domino).
•
LotusScript (and/or Java) for powerful server-side processing such as to dynamically create HTML pages or perform post-submit processing.
The history of client-side scripting In the beginning, the idea of a web browser was to display crudely formatted text and images using a simple markup language (HTML) and provide hyperlinks to other pages. It only took a few years for this simple display-only approach to change drastically to where the browser is now a universal user interface for custom applications. Scripting in browsers is implemented as a runtime interpreted language that cannot run outside the context of an HTML page interpreted by a browser. This is because the code is actually sent in human-readable text along with the HTML content to the browser for local execution. The browser renders the HTML it finds and executes the script from various events. JavaScript has its own development history parallel to but separate from browsers. It should really be thought of as independent from the browser object model because there are browsers that support other scripting languages (e.g. Perl, Java, Python, etc.) and because JavaScript is also used in non-browser products (e.g. Windows Script Host, Groove, etc.).
Topic 1: Browser Objects and JavaScript
13
For simplicity, this course focuses on “JavaScript” as a generic label for the various scripting language variants used in the most popular browsers: •
JavaScript is the scripting language used to script browsers with a Netscape lineage (AOL stopped supporting the Netscape browser in March 2008), such as the newer Mozilla/Gecko-based browsers.
•
Microsoft Internet Explorer uses JScript (as well as VBScript), a JavaScript variant that is COM-aware.
•
ECMAScript (the European Computer Manufacturers Association's ECMA262 language) comes from the Web Standards Project, and is an attempt to standardize the native language elements and language-based objects of browser scripting. Both Microsoft and Mozilla-based browsers claim to be ECMAScript compatible, though each adds extensions that the other cannot interpret. Mozilla, for example, follows as much as possible the ECMAScript standard.
JavaScript is a somewhat full-featured scripting language with variables of several data types, various math, string, equivalence, and Boolean operators, statements, functions, arrays, error trapping, objects, and object events/methods/properties, giving it the ability to perform computations and interact with users via dialog boxes. The JavaScript language objects are used to manipulate data, which may/may not be derived from browser objects: JavaScript language objects
Array Boolean Date
Enumerator Event Function
Math Number Object
RegExp Screen String
Not wanting to be limited to the language primitives, open source and commercial vendors continue to stretch the utility and power of JavaScript: •
New pre-built JavaScript libraries are continually being released (such as Dojo, Prototype, and JQuery), making it easier and faster to develop interactive applications that use AJAX.
•
Popular web sites like Google and Yahoo provide interfaces for services that you can include on your pages and control with JavaScript.
14
Topic 1: Browser Objects and JavaScript
Brief history of browser object models Using JavaScript to code browser behaviors has always been challenging because of the rapid development cycle of browsers. With each browser brand (Internet Explorer, Mozilla-based browsers, Safari, etc.) and version comes a new and improved object model. Because you generally can't control which browser brand or version is installed on users' computers, your code has to either find a lowest common denominator or branch to accommodate the many possible browser brand/version combinations. You’ll learn more about browser compatibility late in this course. When JavaScript was first introduced to browsers, the first object model was the Browser Object Model, now known as the Document Object Model (DOM) Level 0. The early browsers Netscape Navigator 2 and Internet Explorer 3 supported the Level 0 DOM. As browsers developed, Microsoft and Netscape developed competing and incompatible proprietary DOMs in their Version 4 browsers to support Dynamic HTML and Cascading Style Sheets. It would be convenient (but alas impossible) to ignore these models because the differences are both significant and aggravating. While IE continues to support most of its first DOM in its current version, Netscape completely abandoned its version 4 DOM and has replaced it starting with Netscape 6 with the W3C DOM. When Netscape development transferred to the open source Mozilla Organization in 1998, the Mozilla browser continued with implementing the W3C DOM. These are the standards-based, vendor-neutral models promoted by the W3C (http://www.w3.org/DOM/, summarized nicely at http://www.mozilla.org/docs/dom/reference/levels.html): •
DOM Level 1 incorporates and extends Level 0 as well as provides full support for Dynamic HTML (DHTML). Level 1 is supported to some extent by most current "5th generation" browsers such as Netscape 6+ and Internet Explorer 5+ (as well a bevy of standards-based browsers such as Mozilla Firefox and Opera). This is considered the current DOM.
•
In 2000, DOM Level 2 added a style sheet object model for easier access to styles attached to a document. It also introduced an event model and support for XML namespaces. The 5th generation browsers (e.g. Mozilla) support some aspects of DOM Level 2, but not all.
•
In 2004, the W3C published the latest specification for DOM Level 3. (http://www.w3.org/TR/DOM-Level-3-Core). It extends DOM Level 2 primarily to enhance support for XML/XHTML.
Topic 1: Browser Objects and JavaScript
15
Even with standards to follow, it is left up to the browser vendors to implement the standards as they see fit, which in practice means spotty support and proprietary extensions (go to http://www.w3.org/2003/02/06-dom-support.html to see what DOM modules your favorite browser supports). It is also up to web page developers to code their pages to work with both current and past browsers. Note: The bulk of this course is based on DOM Level 0 and then turns to DOM Level 1 in a later Topic that discusses Dynamic HTML (DHTML).
Launch browser from Lotus Notes Which browser Notes launches when you hit a URL found in a Notes document (including a message) depends on User Preferences: •
Notes 8 Standard configuration. Notes uses the browser that is set as the default browser in the operating system. The choice you have in Preferences is whether to launch that browser in a Notes window tab or in its own window outside of Notes.
•
Notes 8 Basic configuration and previous versions of Notes. The current Location document determines which browser opens, and you have more choices than with the Standard configuration. You can choose any browser to launch in an outside window, or in the case of the “Notes browser” or IE (“Notes with Internet Explorer”), open it in a Notes window tab. FYI, the “Notes browser” is the least standards-compliant browser you can pick (it is uses an early Mozilla/4.0 rendering engine that uses ECMAScript 1.4, though it lacks a complete browser DOM, as you will see below) but is tied into the Personal Web Navigator 6.0 application, which has some minor advantages). We won’t even attempt to code for the Notes browser in this course. Fortunately “Notes with Internet Explorer” is the default and best browser to use.
Don’t confuse the browser launched by Notes to render web pages with the Notes rendering engine used to display Notes documents. The Notes rendering engine itself supports some of the DOM objects and a limited range of JavaScript.
16
Topic 1: Browser Objects and JavaScript
Browser Object Model (DOM Level 0) Virtually everything in a browser environment as well as the content on an HTML page is considered an object, with its associated events, properties, and methods. The shaded boxes in the browser DOM represent browser objects, while the unshaded boxes represent HTML objects that are created using HTML tags: navigator
window
location
frame
document
history
image
link
form
anchor
applet
button reset submit
checkbox radio select
text textarea hidden password
fileupload
submit reset
toolbar, etc.
area
How does this relate to what a user sees on a web page? This diagram shows the relationship between the HTML that makes up a web page and the nested hierarchy of objects: Navigator Window Document (HTML page)
navigator object window object document object
<TITLE>My Page <script language="JavaScript" type="text/javascript"> function HelloWorld(getText){ alert(getText); } Discussion Item
JavaScript
form object element objects (field/buttons)
The Navigator object represents the browser itself. The Window object contains the Document object, which in turn contains elements, including one or more Form objects, each containing one or more Element objects.
Topic 1: Browser Objects and JavaScript
17
JavaScript vis-a-vis browser objects JavaScript has access to the methods and properties of browser objects. Although the various browsers differ slightly in their object models, there is a large common base of language, browser, and HTML objects that they all share. The whole idea behind JavaScript is to create interactive web pages that don't require a round trip to the server for server-side code execution. An equally important goal for dual-client applications is to provide equivalent features and experience for both audiences. With its ability to work with these language, browser, and HTML objects, using JavaScript you can: •
automate navigation
•
dynamically generate HTML content
•
change the location and format of text and graphics using Dynamic HTML (the combination of HTML, Cascading Style Sheets, and JavaScript)
•
show Field-level help in the browser status bar or a popup window as they hover over links
•
prompt users for information using built-in alert, confirm, and prompt dialog boxes or through simulated @DialogBox or @Picklists with data fed from Notes documents or Views
•
perform simple Field translation and validation interactively at the browser without refreshing the Form, which requires a round-trip and a page refresh (Domino runs the Field Input Translation and Validation formulas and returns a new page showing the results)
•
change Form open behavior by calling a JavaScript function in the onload browser event handler; the Form submit behavior can be changed by calling a function in the Submit event handler
•
create or destroy windows (such as to simulate custom dialog boxes)
•
dynamically update window and Frame locations and content
•
store user preferences in cookies on the local computer for later recall or passed as part of URL links for page pre-processing based on the preferences.
All of this is possible because JavaScript has full access to browser objects.
18
Topic 1: Browser Objects and JavaScript
Note: Again, because Lotus Notes also supports JavaScript (though with fewer browser objects), the goal for the developer is to write applications that work for both browsers and Notes without recoding. In practice, you will find this possible for very basic things only, since Notes just doesn't completely support all the browser objects.
Mozilla’s DOM and JavaScript object Inspector Want to know everything there is to know about the DOM and JavaScript objects on a web page? Open the page in the DOM Inspector that comes with Mozilla Firefox or Netscape Browser 8+. How you open the tool varies by browser. In Firefox, it is Tools - DOM Inspector. In the left pane, you can navigate the DOM nodes and see the object details in the right pane:
You can switch to view Stylesheets or JavaScript Object properties. We think this tool is immensely helpful in understanding both the DOM and JavaScript object hierarchies. As the course progresses you will be working with all three types of objects (DOM, Stylesheet, JavaScript).
Topic 1: Browser Objects and JavaScript
19
Domino as a Web server Domino Designer is what you use to create design elements that combine HTML and JavaScript, but it is the Domino Server that is responsible for serving the pages to browsers. Domino is made up of a core executable and a number of add-in tasks to fulfill various functions, such as database access, replication, mail routing, etc. Together, these tasks contribute to the list of Domino Services and Objects, as shown in this diagram: Domino Server Domino Services and Objects (directory, security, replication, mail, DECS, etc.)
APIs Protocols
Notes RPC
NRPC
Web Server
HTTP
Corba
IIOP
Mail & Directory
POP IMAP SMTP LDAP
Domino provides client access via various protocols to various APIs. Browsers access the Domino services and objects through the Domino Web Server using the HTTP protocol.
The Domino "Web Server" The Domino "Web Server" is made up of the Application Server and the HTTP engine. This diagram shows the relationship between the server components and the URL parsing performed by the HTTP server: Domino "Web Server" Domino Web Application Server
.nsf in URL
.html CGI/PERL
Domino HTTP Engine
HTTP w/ or w/o SSL V3, X.509
TCP/IP Network
Browser
20
Topic 1: Browser Objects and JavaScript
Domino Databases (.NSF)
•
•
HTTP Server. The native Domino HTTP server task is much like a typical HTTP server, in that it parses URL requests from browsers and interprets/returns pages (which contain HTML and client-side scripts) or refers calls to other interpreters (CGI/PERL) or servers (such as to streaming video servers). In addition to HTTP services, Domino also includes: •
user authentication from the Domino Directory, X.509 certificates, or LDAP referrals
•
connection, server request, and cookie logging
•
URL mapping and redirection
•
authentication realms, single sign-on (between Domino Servers and between Domino and Websphere) and session-based authentication (you can create custom forms to enter name and password)
•
HTML file protection
•
Internet Cluster Manager for load balancing and failover
•
Domino Web Server API filters (DSAPI)
•
ability to run Java Servlets.
Application Server. If the URL includes ".nsf", the commands appended to the URL (such as ?OpenForm) are passed to the application server for processing. The application server generates pages on-the-fly using the logic coded in the application and returns standard HTML back to the HTTP server to deliver to the browser. The server also responds to: •
Web Services requests (over HTTP) and packages responses in SOAP.
•
Requests for View data to be returned to the browser as XML or JSON (in response to the ?ReadViewEntries URL command).
Keep in mind that the HTTP server task and the application server both use the same Domino databases; as such, your applications, if designed correctly, can service both Notes clients as well as browser clients.
Topic 1: Browser Objects and JavaScript
21
Third-party Web server plug-ins There are two ways to look at integrating the Domino Web Server with other web server products: •
It can plug into third-party web servers such as Microsoft IIS (the first certified server) and IBM HTTP Server (IHS) (more in the future). Whereas the third-party web server handles static pages and other resources (ASP, JSP, CGI, etc.), calls to .NSF databases are passed to the Domino Web Server, even if the two servers are separated by a firewall (third-party web server sits in the DMZ while Domino sits inside the firewall).
•
More third-party plug-ins can run under the Domino Web Server due to its extended DSAPI support. The IBM WebSphere Application Server's servlet engine (J2EE application server), for example, can plug into the Domino Web Server (this actually started with Domino 5.0.5 but has been enhanced with each revision). The benefit—in addition to running servlets—is that WebSphere can use the Domino Directory for authentication via LDAP and users can sign on once to either Domino or WebSphere and their authentication credentials are carried between the servers.
Exercise: Create project databases In this exercise you will install the example/exercise database and other resource files on your local hard drive and then create a non-replica copy of your example/exercise database on the classroom server. Step
Action
1
Instructor will tell you to find the course data installer (INSTALL.EXE).
2
Run the installer so that the files are copied to your local hard drive in a folder under your Notes \Data directory. The files are saved to the local \Data\DDJS8 folder.
3
The Instructor has registered you as a Domino user and has given you the right to create new databases on the classroom server. The instructor will provide your Notes user name, Notes User ID password, and Internet Password (is set to be the same as your Notes password).
22
Topic 1: Browser Objects and JavaScript
Step 4
Action Follow these steps to create a new non-replica copy of the DDJS8 Demo database on the Domino Server that you will use in all the exercises: • Start Lotus Notes. • Choose File – Application – Open and browse to the local folder containing the DDJS8 Demo database. Open the database. • With the database open, choose File – Application - New Copy. • Specify the classroom server name given by the Instructor as the location for the new database. • Change the file name to a unique name, perhaps including your initials, such as JJBExercises.NSF. • Enter a title that you will remember, such as JOE's Exercise Database. Note: In all exercises, this database will be referred to as Your Exercises database. Where you see this name, substitute your database name. • Deselect Access Control List, as you want yourself and the Domino Server to be listed as Managers in the ACL. • Leave all the other settings at their defaults. • Click OK to create the database (again, you have been given rights to create a new database on this Server).
5
If not open already, open the Your Exercises database on the classroom server.
6
Choose File - Application - Access Control. For now, click the -Default- setting and select Author access. Also select the can create and delete documents rights. Click OK to save the settings.
Topic 1: Browser Objects and JavaScript
23
Step
Action
7
Switch to your browser to test the ability of Domino to find the Your Exercises database. Enter this URL to create a Discussion document: http://server/jjbExercises.nsf/discussion?openform
Be sure to substitute the server and directory/database names so that you open your copy of the database to the Discussion Form. If the Form opens, you are successful and are ready to continue.
8
24
When everyone has finished creating their database on the server, the Instructor will use Domino Administrator to sign all the databases using the Instructor ID. (There are a couple of Agents that need signing before they will run on the classroom server.)
Topic 1: Browser Objects and JavaScript
Topic 2: Coding JavaScript in Domino Designer Key points This Topic looks at how to code HTML and JavaScript in various design elements using Domino Designer. It also explains how Domino Server interprets the design you create and renders pages containing HTML and JavaScript.
HTML page structure The Domino Designer development environment integrates HTML and JavaScript so that the code you write is properly translated and placed in the proper context on the HTML page when sent to the browser as well as to Notes. Domino builds HTML forms on-the-fly using the Form design as its set of instructions. It outputs fairly generic HTML, taking care to make the necessary conversions to produce a reasonable facsimile of the original design. To facilitate talking about how Domino interprets a Form and converts it to HTML sent to the browser, let's look at a simple Form, DesignToHTML Form, from the DDJS8 Demo database:
Here is what the Form looks like rendered in a browser:
Topic 2: Coding JavaScript in Domino Designer
25
Here is the HTML source sent down from Domino, as viewed by the browser. This is everything the browser has to work with--the HTML to display the page and the JavaScript to make it interactive (line numbers were added for this discussion): 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 26
DesignToHTML Test Form <script language="JavaScript" type="text/javascript"> <script language="JavaScript" type="text/javascript">
49. 50. 51. 52. 53.
54. 55. 56.
57. 58. 59. 60. 61. 62.
// --> DesignToHTML
Subject:
This page sent to the browser from Domino contains all the HTML and JavaScript the browser needs to work with the Form, including a button to submit the form back to the server. Even though the HTML page is sent as a whole, the job of programming the various elements is done in many places within Domino Designer. This diagram shows just one instance of how the JS Header event ends up being placed in the section of the HTML page:
Topic 2: Coding JavaScript in Domino Designer
27
This table shows where the work is done in Domino Designer, identifying the relevant line numbers (if present) from where everything ends up in the source HTML source shown above: Line # 1-3 4 n/a
5
HTML Source
Designer Location
Domino adds the DOCTYPE, HTML, and HEAD tags automatically.
Server Generated
The Window Title event formula determines the <TITLE> placed in the
Window Title event
Additional tags in the , such as <META> tags including keywords or document refresh information, link information, language, or other information that defines the document, can be defined here using @Functions.
$$HTMLHead Field or HTML Head Content
Demarcate the part of the HTML that the language interpreter should pay attention to.
Server Generated
While most browsers assume that <SCRIPT> (without the language argument) is JavaScript, it is a good idea to specify the language in the event the file is interpreted by a browser that can process other or multiple languages. 6, 22
It is a good idea to include the comment symbols () to hide the code from browsers that don't support or have disabled JavaScript. To these browsers, this is just commented HTML. Compliant browsers can read the code with no problem. The "//" is added as a JavaScript comment so that the browser doesn't try to evaluate the "-->", which would result in an error. You will learn more about browser compatibility in a later Topic.
28
Topic 2: Coding JavaScript in Domino Designer
Server Generated
Line # 7-21
HTML Source
Designer Location
JavaScript functions entered into the block of the HTML page. Putting them here makes them globally available throughout the document and can be called from other windows or frames by referencing the container document as the source of the code.
JS Header event
Also note that any variables declared in the are global to all other JavaScript on the page. Note: Though grouped together with the other JavaScript events in Domino Designer (shown with circles in the Object Browser), the JS Header is NOT a browser object event handler, but rather a place to write JavaScript functions that will be placed in the section of the page. 2450
JavaScript functions generated by the Domino Server to handle the actions taken by buttons and Actions written using the Function Language. You cannot modify or delete this code.
Server Generated
Note: The Database property Web access: Use JavaScript when generating pages must be set (this is the preferred setting when coding for the web) for this to happen. 52
Used primarily to set various attributes such as the colors of the background, text, links, visited links.
HTML Body Attributes event
53
The tag, which includes the HTTP command to Post the Form when submitted as well as the container Form name (preceded by an underscore) for easy reference in the code.
Server Generated
All of the elements in the Form (Fields, buttons, images, etc.) are included in the block.
Topic 2: Coding JavaScript in Domino Designer
29
Line #
HTML Source
Designer Location
54
A hidden Field, used as part of the Servergenerated code to handle button clicks (lines 21-47)
Server Generated
56
The Subject Field definition, which includes onchange, onblur, and onfocus event handlers.
onChange, onBlur, and onFocus events
The reference to document.forms[0].Subject passes a reference to the Subject Field object found in the first in the array of Form tags in the document to the upCase() function, which in turn uses the value property to access the Field contents. This could also be written as: upCase(document._DesignToHTML.Subject)
using the Form name, or using the selfreference to the current object: upCase(this)
Other attributes appear in the Field, such as MAXLENGTH and SIZE.
57
The HelloWorld button, which demonstrates how to call a function.
HelloWorld button
58
The Save button that calls the confirmSave() custom function (defined in JS Header) from its onclick event handler.
Save button
59
Another hidden Field, SaveOptions, set to "1", meaning the document will be saved when submitted.
Computed when composed Field
The Form property Generate HTML for all fields must be set to make hidden Fields available to JavaScript even though hidden from the user.
30
HTML Attributes "event"
Topic 2: Coding JavaScript in Domino Designer
Line # 6062
HTML Source
Designer Location
The end of the Form, Body, and HTML blocks.
Server Generated
Code your own HTML Domino converts the WYSIWYG text and design elements you add to a Form or Page using Domino Designer, such as the Form itself, the window title, fields, and buttons to HTML, before sending it to the browser. To manually add HTML to a Form or Page, you can: •
Mark selected text as pass through HTML (either from the Text menu or by surrounding the passthru HTML with braces) so that you can add your own HTML formatting tags. Note: If you want Notes to render the HTML, be sure to set this property on the Form/Page properties Info tab:
Tip: Choose View - HTML Frame to use the embedded HTML editor to edit the currently selected passthru HTML. •
Set the Web access\Content as HTML on the Form properties Defaults tab:
You must then hand-code the entire Form/Page, as Domino will perform no conversion and assume everything is HTML.
Topic 2: Coding JavaScript in Domino Designer
31
Other sources of HTML In addition to HTML placed on Pages and Forms, there are two other places from which Domino can serve HTML: •
HTML files stored as shared file resources.
The advantages of storing HTML files inside the database are:
32
•
The files are stored securely, with access controlled by the database ACL.
•
Files can be replicated to other servers to increase availability and scalability as well as to laptops for disconnected use.
•
Deployment is easy because the files are already with the database that uses them.
•
You can leverage the use of a Master Template database from which all HTML (as well as image, CSS, and .JS files, other web-related files, as well as all design elements) can be sourced and refreshed from nightly.
•
Coding is easy because the location of the files is more predictable and relative URLs allow the database to be moved from server to server and still work.
Topic 2: Coding JavaScript in Domino Designer
•
Because the Domino Web Server also serves HTML pages stored in the file system (by default under the \DATA\DOMINO\HTML directory), you can interleave Pages, Forms, and Views dynamically generated from the Domino Application Server. Domino extends its security model to protect HTML files. Use the Internet Sites View to create a File Protection profile for a particular directory and/or file:
You can set an ACL to control who has rights to read/execute and read/write/execute files, and who has no access. Domino also lets you include HTML files in its Domain Search facility. Getting JavaScript into the HEAD tag When coding for the browser using Domino Designer, the important thing to remember is that the result must follow the rules that the browser HTML and JavaScript interpreters enforce. From the design side, it doesn't really matter how you get the HTML and JavaScript on a Form as long as when it is sent to the browser it results in a page that contains valid HTML and JavaScript. Caution: Do not use two or more techniques that overlap, such as coding the HTML Head Content and the JS Header and the $$HTMLHead Field with JavaScript functions. Though in many cases it will work, you may get unpredictable results.
Topic 2: Coding JavaScript in Domino Designer
33
With this in mind, there are a number of ways to code JavaScript using Domino Designer. Which one you choose to use is up to you, although be warned that the Notes client only interprets JavaScript that has been written in the JS Header event. There is no one "right" way and often you will find yourself mixing and matching techniques depending on the requirements at hand. You can see these techniques in action on the JavaScriptOnForm Form in the DDJS8 Demo database: •
HTML Head Content. This "event" must be coded using the Function Language, the result of which is placed in the section of the page sent to the browser. The result of the HTML Head Content formula must be a string containing proper HTML, including any JavaScript functions you want to include. Although you generally use the JS Header event to include JavaScript functions in the header, the advantage of writing JavaScript functions here is that you can easily mix Notes Field values and @Formulas into the JavaScript using Formula Language string concatenation (+), for example: "<SCRIPT LANGUAGE=\"JavaScript\">function sayHiUser1(){alert(\'1: " + @UserName + "\')}"
Notice that you need to add the <SCRIPT> tags as these are not assumed, and that getting the mixture of Formula Language quotes and JavaScript quotes can get a little tricky. All quotes embedded in the JavaScript must be preceded by the formula language escape character "\". The advantage of this technique, however, is that you can use the full Function Language intermixed with the JavaScript code. The other reason for the HTML Head Content event is for other tags you may want to include in , such as <META> and <STYLE> tags. •
34
$$HTMLHead Field. The use of the HTML Head Content event supercedes the old reserved $$HTMLHead Field (a hidden Computed for display Field placed at the top of a Form), but it is still supported for backwardcompatability.
Topic 2: Coding JavaScript in Domino Designer
•
JS Header. The JS Header event is the preferred location for your JavaScript functions. This event accepts (and performs syntax checks on) JavaScript. The resulting code is automatically placed on the page in the section with the necessary <SCRIPT> tag. If you need to use a Notes Field value or @Function in the JavaScript, you must do so indirectly by coding a (hidden) Field and then read the value property of the Field using JavaScript. For example, if you want the user name from the @UserName function, you cannot do so directly in the JS Header event. You must create a hidden, computed Field (in this example named getUserName) that uses the formula and then access the Field on the HTML form using the Field's value property: function sayHiUser0(){ form=document.forms[0]; alert('0: ' + form.getUserName.value)}
Note: If you want JavaScript functions to be visible to Notes, you MUST put them into the JS Header event as Notes does not compute the HTML Head Content event or $$HTMLHead Field.
Exercise: JavaScript function You will learn much more about JavaScript language elements in the next Topic and about functions in later Topics as the course progresses. In this exercise, you will simply type a JavaScript function in the JS Header event to give you some experience using the editor. You will call the function in the next exercise. Step 1
Action Back in Domino Designer, switch to the Forms List and create a new Form. Open Form properties and name the Form Topic2.
2
Expand the object events for the Form and click the JS Header event.
3
Select Web as the runtime client and JavaScript as the code type. Note: We are not going to assume that any JavaScript will be run the same way by Notes, so Common JavaScript is not a good option.
Topic 2: Coding JavaScript in Domino Designer
35
Step 4
Action Enter this JavaScript in the Programmer's Pane: function saySomething(msg) { alert(msg); }
This code shows two things: • The end of most lines is a semi-colon. Each code statement is typically entered on a new line so that it is more readable; any extra whitespace (new lines, tabs) between lines is ignored by the runtime interpreter. Caution: In some browsers, lines of JavaScript code cannot exceed 254 characters. To avoid this limitation, use variables to assign intermediary values and concatenate them later in the code. • The Programmer’s Pane colorizes the code. Right-click and choose Programmer's Pane Properties to change the colors and fonts. Note: For a good introduction to common JavaScript coding errors, read http://javascript.internet.com/debug-guide.html, especially the section titled “Six mistakes everyone makes”. You will learn at the end of this Topic how to handle run time errors. 5
Save the Form. In the next exercise you will call this function from a button and then test it.
36
Topic 2: Coding JavaScript in Domino Designer
Getting JavaScript onto an HTML page Now that you know to put global JavaScript functions and variables into the section, the next task is to write the JavaScript that calls those functions. There are several ways to get JavaScript on the HTML page depending on when/how you want JavaScript to execute: •
Form, Hotspot, button, Action, Image, etc. events. When you define these elements and specify JavaScript as the language, Designer opens the entire set of event handlers to coding. When you create a button, for example, the button events appear in the object list:
If you were to open the Form in a browser and look at the source HTML, you would see that Domino adds the event handler code to the tag defining the button:
Note: You will learn more about browser events in a later Topic.
Topic 2: Coding JavaScript in Domino Designer
37
•
Text - Pass-Thru HTML. Although most of your code will appear in the JS Header and element events, it is also allowable to put <SCRIPT> tags outside the in the section. This script executes when the is loaded. You must add your own <SCRIPT> tag and mark the code as pass through HTML. This screen capture shows two JavaScript functions written on the Form:
Because you can intermix Computed text and Fields into the in-line script, you can in this way dynamically generate the JavaScript during run time. In this example, the first function references a Field on the Form using JavaScript methods; the second function uses a Notes Computed for display Field placed in the JavaScript to compute part of the JavaScript. In-line JavaScript is often used to dynamically output HTML in the same place as where you have the <SCRIPT> tag. For example, this script on the JavaScript on Form Form in the DDJS8 Demo database displays an email address in such a way that makes it harder for harvesters to find the address: <script language=javascript>
Caution: Be sure to set the font of the in-line code to 10 pt. Default Sans Serif. If set to any other font type or point size, the resulting HTML created by Domino may insert ,
, or tags that will result in JavaScript errors. Also, be sure NOT to use the Enter key to break a line of code except after a ";", "{", or "}". If you use Enter, Domino inserts a
tag when it interprets the HTML page, which is not valid inside JavaScript code. Use Ctrl-Enter instead.
38
Topic 2: Coding JavaScript in Domino Designer
Caution: When setting the Pass-Thru HTML property, be sure to highlight all the characters when applying the Text property, as the property applies on a character-by-character basis (as opposed to paragraph by paragraph). If there is a button, table, Computed text, or a Hotspot either standing alone or in the stream of pass through HTML, turn OFF the Pass-Thru HTML property or the element will be ignored when Domino renders the page. Conversely, you can set the output of a Field or Computed text to pass through HTML by selecting the space before, the Field, and the space after before you apply the property. •
Treat document/page contents as HTML. This is an entirely manual method, and generally serves no practical purpose. When you enable this Form property, you must code every HTML tag, including the tag, on the Form or Page. Although you can use Fields (on Forms) to compute the HTML, nothing else is automatic--no event code is included, no buttons or tables are converted--and the Domino Server strips the Form down to pure text, ignoring all text formatting, fonts, tables, and Hotspots. The other problem with using this Form property is that it is impossible to save a document when set. The Form can only be used by calling the ?readform URL command and any Submit button will fail (you will get the error message Error 500, HTTP Web Server: Application Exception Documents treated as HTML cannot be edited). In past versions of Domino, these Forms were used to create pages with embedded view or navigator elements or to create documents that stored framesets. But Pages and FrameSet design elements have taken the place of this workaround. Note: Any of the special web-related Field names, such as $$HTMLHead or $$Return will not work if you have set this Form property. Further, these Fields should be set as Computed for display and hidden when reading and editing (but NOT hidden from web browsers). Tip: If all you need is a static HTML page, consider using a Page or simply adding the HTML page to the Shared Resources - Files area of the design; or if you don't want it in an NSF, ask your Domino Administrator to put the file in the \HTML directory on the Server.
Topic 2: Coding JavaScript in Domino Designer
39
•
WebQueryOpen event Agent. If you would rather generate JavaScript on the fly using LotusScript, you can do so by setting a Field on the Form to a string that contains the in-line JavaScript code. Of course the Field must be marked using the Text - Pass-Thru HTML property. For example:
Then, write the Agent code (in LotusScript or Java), for example:
Finally, put the Agent name in the formula in the WebQueryOpen event on the Form, for example:
The final output of the Agent sets the JS1 Field. Notice that the code relies on a Field value (getUserName) to get the user's real name. This ensures that the actual browser's user name and not the server name or Agent signer name is returned (which is the case if you use the NotesSession object UserName or EffectiveUserName properties). Writing JavaScript using LotusScript also makes for an interesting time when dealing with literal quotes. To get around this, use the vertical bar symbol in LotusScript whenever literal quotes are used. Also notice the use of the ErrorHandler routine that writes to the LSErrorMessage Field. Since the WebQueryOpen Agent cannot output to the browser as can the WebQueryClose Agent, this gives you the ability to troubleshoot the code.
40
Topic 2: Coding JavaScript in Domino Designer
•
Use of @Functions and automatic conversion of @Commands to JavaScript. There are a number of very web-specific @Functions that return information that would be more difficult or impossible using only JavaScript (@ClientType, @BrowserInfo, @WebDBName, @GetHTTPHeader, @SetHTTPHeader, @UrlQueryString, and @DbCommand) and perform computations with the full power of many unique @Functions. There are about 40 or so @Commands that can be used in buttons, Action buttons, and Action Hotspots. Domino will not perform this conversion of @Commands to JavaScript equivalents for you unless you have the Database property Use JavaScript when generating pages set:
Using @Commands instead of JavaScript dramatically speeds development of applications that run on all modern browsers as well as Notes. You will learn more about this conversion in a later Topic. Note: Search Domino Designer 8 Help for "@Functions on the web" and "@Commands on the web" for a thorough discussion of how @Functions and @Commands are used (or disallowed) in applications written for browsers.
Topic 2: Coding JavaScript in Domino Designer
41
Exercise: Create a button In this exercise you will create a button that calls the function you created in the previous exercise. Follow these steps to create the button: Step
Action
1
Open the Topic2 Form in the Your Exercises database.
2
Create a new button on the Form. Name the button Hello World.
3
Expand the events for the button.
4
Click the onClick event for the button and select Web as the runtime client and JavaScript as the code type.
5
Enter this JavaScript in the Programmer's Pane: saySomething('Hello, world!')
This is what the code will look like when you are done:
42
6
Save the Form.
7
Choose Design - Preview in Web Browser - Internet Explorer or the Internet Explorer Preview tool:
8
The Form opens in the browser.
9
Click the Hello World button to make sure it works properly.
Topic 2: Coding JavaScript in Domino Designer
Troubleshooting button problems Apart from problems with the actual JavaScript that you write, there are several Domino-specific problems you may encounter when adding a button to a Form or Page: •
If you use an @Function or @Command that cannot be converted or you made some other coding error, the action or button won't appear in the browser. This is your clue that something is wrong.
•
If the button is added in the middle of text marked as pass through HTML, the button won't appear. Also check to see if the Hide When properties are set correctly for the paragraph so that it is not hidden for web clients or in Read/Edit mode (depending on the purpose of the button).
•
If you have put your code under the JavaScript for the Notes client (instead of the for web) or didn't mark the code scope as Common JavaScript. The result is that when you go to test the code (and look at the HTML Source), your changes are not being sent to the browser.
JavaScript libraries Once you have been working with JavaScript for a while, you will find that there are routines common across many Forms or Pages and between applications. It makes little sense to repeat and maintain them in every design element where you use them. The answer is to store the common functions in a .JS file that is downloaded by the browser at run time. The .JS file must be saved as ASCII text and cannot contain any HTML--it only contains JavaScript functions, for example this file named Jslib.js:
function sayMessage(message) { alert(message) }
In ordinary browser applications, the .JS file is stored in the file system of the Web Server and linked to with this tag in the block: <SCRIPT src="Jslib.js" language="javascript" type="text/javascript">
But with Domino, you can incorporate the .JS files into the database design as a Script Library.
Topic 2: Coding JavaScript in Domino Designer
43
Once you add the Script Library to the database and reference it properly, you can call the functions from anywhere on the Form or Page as if they were defined in the JS Header event. The added benefit of separating large JavaScript library files from other design elements is increased performance because browsers can cache the library file rather than taking time to download it every time. This also reduces Server overhead and network traffic. Follow these steps to create and reference a JavaScript library: Step
44
Action
1
Expand Shared Code in the object browser and click Script Libraries to open the Script Libraries list.
2
Click the New JavaScript Library button.
3
Right-click the Programmer's Pane and choose Import:
Topic 2: Coding JavaScript in Domino Designer
Step
Action
4
Select the desired .JS file from the location where you installed the course data disk, for example:
Click Import. 5
The code is imported.
6
Press Esc to name and close the library.
7
Now to use the JavaScript library.
8
Open the Form or Page where you want to use the JavaScript library.
9
Click the JS Header event, right-click in the Programmer's Pane and choose Insert Resource.
Topic 2: Coding JavaScript in Domino Designer
45
Step 10
Action Because you are working in the JS Header event, only the JavaScript libraries appear.
Select the desired library and click OK. 11
The reference to the library is inserted into the JS Header:
You can now call any of the functions in the JavaScript library. Remember that the JavaScript library may be coming from another database where it can be centrally coded and debugged, and the new code is always available everywhere you have inserted the Shared Resource.
46
Topic 2: Coding JavaScript in Domino Designer
JS files on Pages If you are working with applications created with Domino Designer 5, you may find .JS files referenced from the file system (this is the traditional way to include .JS files) or attach one .JS file to a Page. The advantage of including .JS files in the database, of course, is that they are replicated and secured by the Server. To include the .JS file, add this formula (that evaluates to JavaScript) to the HTML Head Content event of a Page or Form: db:=@WebDbName; "<SCRIPT SRC=\"/" + DB + "/JSLIB/$FILE/JSLIB.JS\" LANGUAGE=\"JavaScript\">"
In this example, the current database contains a Page named JSLIB to which the JSLIB.JS file is attached. If necessary, you can change the database name to point to another database. If the Page is stored in the current database, you can shorten the reference to: "<SCRIPT SRC=\"JSLIB/$FILE/JSLIB.JS\" LANGUAGE=\"JavaScript\">"
To see this example in action, open the TestJSFile Page in the DDJS8 Demo database with this URL: http://server/DDJS8demo.nsf/testjsfile
JavaScript library security At some point you will want to think about stopping just anyone from using your JavaScript libraries. You can do this with the usual Domino security mechanisms or programmatically using techniques found at http://www.javascriptkit.com/javatutors/externalrestrict2.shtml. The basic idea is to compare the current URL with a list of permitted URLs or IP domain names.
Syntax checking As you may have discovered, Domino Designer performs simple syntax checking when you enter JavaScript in the events that accept JavaScript. Although syntax checking is very important (as most errors end up being the result of mismatched quotes/braces/parentheses or due to capitalization errors), there is no interactive debugging capability.
Topic 2: Coding JavaScript in Domino Designer
47
Runtime error reporting Browsers typically have runtime error reporting, letting you know where the interpreter found the problem, this example from Internet Explorer 7 (assuming you have enabled Display a notification about every script error on Internet Options on the Advanced tab):
If you have disabled error notification, you can still see error messages by doubleclicking the error icon at the bottom of the page:
48
Topic 2: Coding JavaScript in Domino Designer
In Navigator, the JavaScript console (Tools – JavaScript Console) shows a running history of errors until you clear it:
Mozilla Firefox an Error Console (Tools – Error Console) that is probably the most informative and easiest to use among the various browsers:
Topic 2: Coding JavaScript in Domino Designer
49
Microsoft Script Editor In previous versions of IE you had to download and install the Microsoft Script Debugger, but starting with IE7, the Script Editor is included in Microsoft Office XP (and later, and you must choose to install the Office Tools\HTML Source Editing\Web Script\Web Debugging tool) or other Microsoft products like Frontpage. You must also enable script debugging in Internet Explorer 7 under Internet Options on the Advanced tab by de-selecting this option:
After it is enabled, restart Internet Explorer. Now when IE encounters a scripting error, you are asked if you want to debug the errors:
50
Topic 2: Coding JavaScript in Domino Designer
Click Yes to launch the Script Editor, which identifies the first problem:
Note: If the Script Editor doesn’t launch, this means the Windows Machine Debug Manager hasn’t attached the Script Editor to the Internet Explorer process. To correct this problem, open a Command Window to the C:\Program Files\Common Files\Microsoft Shared\VS7Debug folder and run these two commands:
Reboot Windows. Return to Internet Explorer and choose View – Script Debugger – Open. Now you should be prompted to choose Microsoft Script Editor as the default debugger:
Click Yes. The Microsoft Script Editor will start, but just exit out of it for now. Topic 2: Coding JavaScript in Domino Designer
51
The Script Editor provides some degree of usefulness for debugging JavaScript embedded in NSF files. Because it is a client-side debugger, you can often find the error, but then you must go back to Domino Designer to fix it, and then save the changes and try again. Note: The problem in many cases, however, is that these tools do not play well with JavaScript that is buried in NSF files since they cannot write to the file. But at least you will gain more information about problems than using no tool at all. You can step through the code and set break points that trigger when you refresh the page. This helps you trace code paths and to check the logic of the code. You can refresh the page back at the browser to see the code stop at a break point. Probably the most useful feature is that the status bar shows the line number so you can easily find where the error occurred.
Mozilla JavaScript Debugger Mozilla's JavaScript Debugger (code name Venkman) is a powerful (and free) JavaScript debugging environment for Mozilla-based browsers. Choose Tools – Javascript Debugger before running some code:
You can install the latest version from http://www.mozilla.org/projects/venkman/ or possibly https://addons.mozilla.org/en-US/firefox/search?q=venkman&cat=all.
52
Topic 2: Coding JavaScript in Domino Designer
The debugger highlights any errant code, and like the Microsoft debugger, lets you set break points and let you step through the code.
Commercial debuggers We have used SplineTech JavaScript Debugger (http://www.javascriptdebugger.com/) and found it quite useful. Another option is Microsoft Visual InterDev, which provides a greater range of debugging capabilities.
A newer version is Microsoft Visual Web Developer 2008. As far as we can tell, the Express Edition is free and includes a debugger (http://www.microsoft.com/express/vwd/). Note: Also see http://support.microsoft.com/kb/q284973/ to edit the Windows Registry to specify which debugger launches in the event you have both Visual Studio and Script Editor installed.
Topic 2: Coding JavaScript in Domino Designer
53
Home grown debugging One of the most useful techniques is simply to temporarily add a JavaScript alert in your code. You can use alerts to pause the execution and report variable values. An alert() is a very useful tool to check your assumptions, especially prior to or inside of looping or branching structures. Keep moving the alert down in the code as you debug your code. Another technique is to create your own debug/logging window. Add the code at the top of JS Header to create a new window and then write to it with variable values or conditions using the document.write() method. Unlike using alert, you can keep the window open and write to it without stopping the program. This is especially helpful when working with loops. You will use document.write in later Topics.
54
Topic 2: Coding JavaScript in Domino Designer
Topic 3: Basic Language Elements Key points Every language has its basic elements and syntax, and JavaScript is no different. This Topic covers some of the basic JavaScript language elements. Note: Domino Designer 8 Help does not offer any JavaScript or browserspecific help. One of the best references for ECMA JavaScript can be found at http://www.devguru.com/Technologies/ecmascript/quickref/js_objects.html.
There you can open reference pages for Functions, Statements, Operators, Constants, and Objects. Under Objects, you can find reference pages for object Methods, Events, and Properties. Everything is color-coded so it is easy to distinguish, for example, between a property and a method when looking at the various JavaScript objects and reading the example code. Another great reference is at http://www.w3schools.com/jsref/default.asp. The best part of this guide is that it distinguishes between what is supported by Mozilla-based browsers and Internet Explorer. It also includes working “TryIt Editor” where you can change the example script and run it.
Walkthrough: Basic elements The best way to explore some of the basic language elements is to actually do some coding and learn the syntax as you go. Follow these steps to explore some of the basic JavaScript language elements and syntax: Step
Action
1
Create a new Form named Topic3 in the Your Exercises database.
2
Create a new button on the Form. Name the button Test.
3
Expand the events for the button.
4
Click the onClick event for the button and select Web as the runtime client and JavaScript as the code type.
Topic 3: Basic Language Elements
55
Step 5
Action Enter this line of script: var getMsg1;
This code shows the creation of a variable. Valid variable names begin with a letter or an underscore character, cannot use spaces, and must not be the same as any JavaScript keyword or HTML tag name. Variable names can include numbers but only after the first character. They should not be prefixed with "html", "css", or "style" to avoid confusing the JavaScript runtime interpreter. Note: Various attempts have been made to standardize variable and function names (such as to include the data or object type in the variable name), but currently there is no standard. By convention, most JavaScript programmers start a variable name with a lowercase letter and then capitalize all following words in the variable name, for example: lastName. 6
In case you were wondering, you can declare multiple variables at once using this syntax: var i, nType, nValue, nName, nID;
We didn’t do this in the current example. 7
Add a line to the end of the existing code and enter this line: getMsg1 = 'hello';
This line assigns a value to the variable using the assignment operator, "=". Strings are quoted in JavaScript, so 'hello' is surrounded by apostrophes, but this could also be written as "hello", with quotes instead of apostrophes as they are somewhat interchangeable. JavaScript is a loosely typed language; variables do not need to be pre-declared as a specific data type. All unassigned variables are variants; JavaScript determines the data type based on the value assigned. The JavaScript runtime interpreter will perform automatic data type conversion if possible, for example, it will handle this operation by converting the number to a string before concatenation: 'hello ' + 23
56
Topic 3: Basic Language Elements
Step 8
Action Add a line to the end of the existing code and enter this line: var getMsg2 = 'goodbye';
Variables can be created and assigned at the same time using the var keyword. 9
Add a new line and enter this line of script: var msg = getMsg1 + '\n' + getMsg2;
This code shows two things: • The use of the string concatenation operator, "+". • The use of an escape character, in this case \n, which when output to a dialog box, creates a line break. Here are all of the valid escape characters:
10
\b
Backspace
\f
Form Feed
\n
New Line
\r
Carriage Return
\t
Tab
\'
Single Quote
\"
Double Quote
\\
Backslash
Add a line to the end of the existing code and enter this line: Alert ( MSG );
The Alert statement displays one of three built-in dialog boxes. It displays a message and an OK button. 11
Save the Form.
12
Choose Design - Preview in Web Browser - Internet Explorer.
13
The Form opens in the browser.
Topic 3: Basic Language Elements
57
Step 14
Action Click the button to make sure it works properly. In this case you will get an error because JavaScript statements are case-sensitive; Alert is not the same as alert.
15
Return to the code and edit the last line: alert ( MSG );
16
Test the button again in the browser. Again, you will receive an error. This time it is because the variable is incorrect.
17
Go back one more time and edit the last line: alert ( msg );
Variable names are also case-sensitive. MSG is not the same as msg. This will be a real "gotcha" if you are accustomed to programming in languages such as LotusScript in which the case of statements and variables is not an issue. 18
Test the button again in the browser. It should work properly now.
19
Add a line to the end of the existing code and enter these lines: var getBool = getMsg1 == getMsg2; alert ( getBool );
Test the button in the browser. This shows the equivalence operator (double equals) as well as the return value constant false, indicating a Boolean “false”. 20
Return to the code and change the "==" equivalence operator to the inequality operator "!=". Test the button in the browser. The alert displays true. The two variables are not equal.
58
Topic 3: Basic Language Elements
Step 21
Action Add a line to the end of the existing code and enter these lines: var getNo1 = 1 , getNo2 = 2; alert( getNo1 + getNo2 );
You can create and assign more than one variable on a line using the comma operator. This also shows the assignment of number values to two variables. The second line shows the addition of two variables resulting in a sum that is displayed in the alert. JavaScript uses the same arithmetic operators as used in other languages, including: +
Addition
-
Subtraction
*
Multiplication
/
Division
%
Modulus (e.g. myMod=18 % 4; )
()
Precedence (parentheses)
++ Increment the variable value by 1 --
Decrement the variable value by 1
+= Aggregate (add) operator *=
Aggregate (multiply) operator
Test the button in the browser. Note: Luckily, the alert box is forgiving in that it will convert numbers to a string; you will see later how to convert numbers to strings to be more precise in your handling of data types. 22
Add a line to the end of the existing code and enter this line: alert( typeof(getMsg1) + '\n' + typeof(getBool) + '\n' + typeof(getNo1) );
Test the button in the browser. This shows the use of the typeof function, which returns the data type of an expression.
Topic 3: Basic Language Elements
59
Simple data types There are several simple data types in JavaScript. Data Type String
Assignment var firstName = 'Mary'; (preferred) var firstName = ‘Joe’;
Number
Integer: var qty = 123; Floating point: var price = 123.34; Note: JavaScript automatically converts a number variable to the correct type (integer or floating point) if you perform mathematical operations on variables of different types. For example revenue=qty*price in this example will result in a floating point data type.
Boolean
var flag = true; var flag = false;
Null
null (no value exists)
Undefined
undefined (a variable is used which has not been defined)
Note: You will see later how to test variables for valid data and how these data types correspond to data read from HTML Fields and written back to Domino. Note: JavaScript also support several complex data types, Object, Array, and Function, which you will learn about in later Topics.
Built-in functions JavaScript comes with a number of built-in functions that create and manipulate data in ways that would otherwise be difficult or impossible to do with basic JavaScript operators. To see the functions in action, create a new TestFunctions Form in the DDJS8 Demo database and click the corresponding buttons.
60
Topic 3: Basic Language Elements
This table describes some of the built-in JavaScript functions: Function Escape Unescape
Description Encodes a string so that it can be used as an (ASCII) URL. All non-standard characters are converted to their hexadecimal escape sequence. For example, spaces are converted to %20. Unescape reverses the process, converting the escaped hex back to non-standard characters.
Eval
Being an interpreted (and not compiled) language, you can programmatically/dynamically generate code and then execute it using Eval. Eval evaluates a string containing JavaScript code and returns the value of the last statement. Eval can be used to build and execute JavaScript on the fly, such as to include user-supplied JavaScript. Note: Eval is also often used to test snippets of JavaScript code. For example, open the EvalJavaScript Form in DDJS8 Demo in Domino Designer and preview in a browser. The code you enter in the Input area is run using Eval.
isFinite isNaN
Used to validate data. isFinite tests an expression to see if it contains a finite and legal number. isNaN is the opposite test, to see if an expression is Not a Number. A mathematical expression will return NaN, for example, if one of the values is not a number, so isNaN is used to trap for the error (you will use isNaN in later Topics for this purpose).
Topic 3: Basic Language Elements
61
Function Number
Description Number converts a string object to a number object. What is a string object? There are two common sources:
parseFloat parseInt
• A text object created by an tag in the HTML. You access the object using something like: var stringObj = document.forms[0].Price.value;
• A string object you create, for example: var stringObj = new String( ‘22’ );
Then use the Number function to create the Number object: var getPrice = Number( stringObj );
If the object cannot be converted to a number, NaN is returned. Note: You will learn more about JavaScript objects in a later Topic. parseFloat and parseInt convert a string to either a floating point or integer number. They are interesting in that the string must start with a number, but anything after the first number can be alphabetic (which is ignored). If the first character is not a number, NaN is returned. String
Converts a string literal or a number object to a string object. What is a number object? There are two common sources: • A text object converted to a number object using the Number function. • A number object you create, for example: var numObj = new Number( '22' );
Then use the String function to create the String object: var stringObj = String( numObj );
Tip: Another way to convert a number to a string is simply to concatenate an empty string to it, for example: var getNum=10; var getStr=getNum+=''
62
Topic 3: Basic Language Elements
Note: There are several built-in JavaScript objects, including Array, Boolean, Date, Event, Math, Object, RegExp, Screen, and String. All the objects have properties and methods that are used to manipulate data. You will look at these objects in a later Topic.
var keyword and variable scope In the walkthrough above, you declared variables using the var keyword. Using var to declare variables is technically not necessary. For example: var getMsg2= 'goodbye';
is the same as: getMsg2= 'goodbye';
What is the scope of variables? Variables declared in the JS Header event, by <SCRIPT> elements in the section, or in any event are global and available to all element events on the page--whether or not they are declared with var or not. This is true except in the case of JavaScript functions that you write. There, the var keyword makes the variable private to the function. Consider this code: price = 24.95; function dispStuff() { var price = 22.00; alert ( price ); } dispStuff(); alert( price );
Two alerts display; the first one displays "22" because the use of var inside a function makes that variable local to the function, temporarily overriding the global variable set outside of the function. The second alert displays "24.95", which is the value of the global variable set outside the function. Now consider similar code with a slight change (in bold): price = 24.95; function dispStuff() { price = 22.00; alert ( price ); } dispStuff(); alert( price );
Topic 3: Basic Language Elements
63
In this case, example, the variable price is assigned inside the function without using the var keyword. What does this accomplish? It reassigns the global variable. So the two alerts display "22" and "22". By not using the var keyword inside the function, you can change existing global variables and create new ones. Note: Some experts suggest that you should declare all variables using the var keyword to make the code easier to read and debug and to prevent variables used in functions from accidentally overwriting global variables. You are not required, however, to use var except inside functions when you want a variable to be private to the function.
Simple dialog boxes There are three built-in modal dialog boxes that are actually methods of the browser's Window object. alert You have already seen the alert dialog box, which displays a message and an OK button. For example: window.alert( 'hi' );
Most browsers let you get away with a shorter version (omitting the Window object reference): alert( 'hi' );
The alert method does not return any value if assigned to a variable, for example: var myVar = alert( 'hi' ); alert( myVar )
The alert method returns undefined, which is a JavaScript constant representing a variable that has been declared or never assigned (or a variable that has never been declared). You can test for this constant with the typeof operator.
64
Topic 3: Basic Language Elements
confirm The confirm method: confirm( 'Do you want to come out and play?' )
displays an OK/Cancel dialog box:
It returns true or false if assigned to a variable. prompt The prompt method: prompt( 'When do you want to come out and play?' , 'Right Now' )
displays a simple input dialog box with OK and Cancel:
If the user enters a value and clicks OK, it returns the string value; if the user clicks Cancel, it returns null. Note: You will see in a later Topic how to create custom dialog boxes using the browser’s window object.
Topic 3: Basic Language Elements
65
Commented code There are three ways to comment code in JavaScript: •
single line comment using two forward slashes at the point in the line after which you want the code commented, for example: // this is a commented line of code
•
comment everything following the marks on a line, for example: alert('hi'); //this is a silly alert
•
block comment, using /* at the start and */ at the end, for example: /* Everything in this block is commented. */
Exercise: Dialog boxes Follow these steps to collect and display user input: Step
Action
1
Open the Form named Topic3 in the Your Exercises database.
2
Create a new button on the Form. Name the button Test User Input.
3
Expand the events for the button.
4
Click the onClick event for the button and select Common JavaScript as the code scope.
5
Enter these two lines of script: var getMsg = prompt ( 'Please enter your name: ' , ''); //collect input alert( 'You name is: ' + getMsg ); //display input
66
6
Save the Form.
7
Choose Design - Preview in Web Browser - Internet Explorer.
Topic 3: Basic Language Elements
Step 8
Action Test the button to see if you coded it properly.
try/catch statement The try/catch statement is the JavaScript equivalent of the BASIC On Error statement (JavaScript 1.5, ECMAScript 3). The idea is that you "try" to execute a block of statements, and if there is an error, jump down to the "catch" block to catch the error generated in the “try” block and in response, run some corrective code. The TryCatch Form in the DDJS8 Demo database demonstrates a simple try/catch statement behind the button: try { myVar.toString(); //produces an error return true; } catch(e) { strErrMsg = ‘Error Number: ‘ + e.number + ‘\n’; strErrMsg += ‘Description: ‘ + e.description + ‘\n’; strErrMsg += ‘Message: ‘ + e.message ; alert( strErrMsg ); return false; }
If there are no errors in the try, the catch is passed over. What does the "e" variable represent? It represents the JavaScript error object, which has the number and description/message properties used in the alert message. You can have multiple try/catch statements and nest them as needed. If an inner try doesn't have a matching catch, the outer catch will be used. There is, however, no "resume" capability. Note: In case you were wondering, "description" and "message" return the same message, but ECMAScript uses message instead of description used by JavaScript. You would obviously need only one message, depending on which version of JavaScript the browser supports. Note: Because try/catch weren't added until recently, older browsers won't recognize them and will generate an error. As such, you can't even include try/catch in code branching; you can only use them in an external .JS file and then select an appropriate .JS file to use for older and modern browsers. Topic 3: Basic Language Elements
67
throw statement In addition to using a standard catch block to handle unexpected runtime errors, you can also define custom error numbers and messages from inside a try statement using the throw statement. The Throw Exception button in the TryCatch Form shows the ability to throw a custom error number to the catch: var getParts; try { getParts = prompt('Enter a number over 3.', ‘’); if (getParts