Main Page

Security restrictions

It would then be possible to catch a thrown error using the JavaScript
try..catch
statement:
var oApplet = document.getElementById(“ExampleApplet”);
var oTextbox = document.getElementById(“txtMessage”);
try {
oApplet.setMessage(oTextbox.value);
} catch (oError) {
alert(“Error caught!”);
}
Because of differences in browsers, it’s not easy to say what will be returned by
oError
. Internet
Explorer returns a JavaScript object representing the Java exception, whereas Mozilla returns the Java
exception object itself. The two browsers have different ways to access the error information: In IE, the
oError.message
property displays the Java exception message; in Mozilla, the
toString()
method
returns a string of Java exceptions, but doesn’t contain the original exception method. In most cases,
however, it’s enough to know that an error occurred.
Security restrictions
Although Java is more powerful than JavaScript, it doesn’t have free reign over the browser when included
in a Web page. Java applets must follow a strict set of rules set out by the browser. (The rules are different
in every browser, although several rules are fairly common.) This behavior is called
sandboxing
.
First, applets are not allowed access to the user ’s file system. This prevents a major security problem if a
malicious applet writer gets an unsuspecting user to open a page containing the applet. By default, this
isn’t possible.
Second, applets aren’t allowed to access resources across domains. This is the same security restriction
placed on the XML HTTP requests discussed earlier in the book.
It is possible to get around these restrictions by digitally
signing
the applet. When an applet is signed, a
dialog is presented to the user asking whether the signature is valid and, in turn, whether the applet
should be allowed enhanced privileges not available otherwise. If the signature is accepted, the restric-
tions mentioned previously are lifted.
You can read more about applet security and signing at
http://java.sun.com/developer/
technicalArticles/Security/Signed/
.
Java-to-JavaScript communication
Not only can JavaScript access methods contained in a Java applet, an applet can actually access JavaScript
objects and functions as well by using LiveConnect. LiveConnect was mentioned earlier as a way for
JavaScript to access Java objects, but it can also be used to more closely integrate applets and JavaScript
using a special Java package:
netscape.javascript
.
This package contains two classes:
JSObject
, which is a Java representation of a JavaScript object, and
JSException
, which represents a JavaScript error. However, the
JSObject
is really the focus of Java-to-
JavaScript communication.
548
Chapter 18
21_579088 ch18.qxd 3/28/05 11:43 AM Page 548


JavaScript EditorFree JavaScript Editor     Ajax Editor


©