Richard Evers, Editor

 

JavaScript's roots date back to early 1995 when Brendan Eich was hired by Netscape® to take charge of a project to design and implement a new language. In this capacity he created a scripting language that eventually became known as JavaScript.

JavaScript was publicly announced by Netscape and Sun® on December 4, 1995 and was included with the release of Netscape 2 in early 1996.

Netscape 3 with JavaScript 1.1 was released in 1996. This release marked completion of Document Object Model (DOM) level 0. DOM is a model that describes how all elements in an HTML page relate to the document itself, which is the upper-most structure. DOM level 0 offered access to a few HTML elements such as forms, and later provided access to images. Modern browsers still provide backward support for DOM level 0.

In 1996 Netscape passed the JavaScript language to the European Computer Manufacturers Association (ECMA) for standardization. In turn, the ECMA created the ECMA Script standard based on the core syntax of JavaScript but failed to include all aspects of DOM level 0.

Over time, ECMA Script kept evolving in line with many of the changes made to JavaScript. This included DHTML support and enhanced syntax. Unfortunately, they largely avoided standardizing the DOM.

Topics within this article include:

Incompatibilities

 

By 1997, difficulties with JavaScript were starting to become apparent largely because of changes made by Netscape and Microsoft® to enhance the language and browser capabilities. While the intent of both companies were honorable in most ways, their efforts resulted in problems with incompatibility that have plagued the community since. Most incompatibilities are not JavaScript issues but are specific to DOM. The JavaScript implementations of most popular web browsers usually follow the ECMAScript standard. The incompatibilies come about by trying to make a browser better than competing browsers. Where the Netscape and MozillaTM based browser such as Firefox® and FlockTM support JavaScript, Microsoft® Internet Explorer supports JScript®. With that in mind, a safer way to develop JavaScript applications for conventional desktop browsers is to remain as compatible as possible to ECMA Script and stay clear of browser-specific DOMs.

BlackBerry Browser and JavaScript

 

The BlackBerry® Browser supports JavaScript 1.0, 1.1, 1.2 and 1.3, and small subsets of JavaScript 1.4 and 1.5. It also supports the ECMA-262 ECMA Script Language Specifications.

The BlackBerry Browser has limited support for style sheets, does not support Dynamic HTML style sheets, and will ignore requests for special effects such as pop up menus.

Support is provided for the following JavaScript objects:

  • blackberry
  • blackberry.location
    (starting in BlackBerry Browser v4.1)
  • navigator
  • document
  • form
  • screen
  • window


Object: blackberry

 

blackberry.network

 

Contains a network identifier as shown below:

  • GPRS
  • CDMA
  • iDENTM
  • WLAN
  • 3G

Example:

document.write("This BlackBerry device is communicating on the
  " + blackberry.network + " wireless network.");

blackberry.location

 

The location object is only available on GPS-enabled BlackBerry devices.

The blackberry.location.GPSSupported property will return true if GPS is supported.

Use the blackberry.location.latitude property to get the current latitude, and the blackberry.location.longitude property to get the current longitude. Both properties are set to zero if GPS is unavailable.

Call blackberry.location.refreshLocation() before retrieving either property to retrieve the most current results. This method returns true on success.

Call blackberry.location.onLocationUpdate() to register a callback method that will be called when Location has been updated. Pass the callback method as the parameter. The method returns true on success.

Call blackberry.location.setAidMode() to set the GPS aid mode to be used by passing 0 for Cellsite, 1 for Assisted or 2 for Autonomous.

Example:

if ( blackberry.location.GPSSupported ) {
    // register callback
    blackberry.location.onLocationUpdate( locationCB );

    setModeCellsite();
//setModeAssisted();
//setModeAutonomous();

} else {
    document.write("GPS not supported");
}

void setModeCellsite()
{
    // set to cellsite mode
    blackberry.location.setAidMode(0);

    // refresh properties
    blackberry.location.refreshLocation();

    document.write("<p>Cellsite Mode</p>" );
}

void setModeAssisted()
{
    // set to assisted mode
    blackberry.location.setAidMode(1);

    // refresh properties
    blackberry.location.refreshLocation();

    document.write("<p>Assisted Mode</p>" );
}

void setModeAutonomous()
{
    // set to autonomous mode
    blackberry.location.setAidMode(2);

    // refresh properties
    blackberry.location.refreshLocation();

    document.write("<p>Autonomous Mode</p>" );
}

// called when location object changes
void locationCB()
{
    document.write("<p>Latitude "  +
        blackberry.location.latitude + "</p>");
    document.write("<p>Longitude " +
        blackberry.location.longitude + "</p>");
}


Object: navigator

 

This object provides information such as name, version, language, mime types, plug ins, and whether JavaTM is supported.

Properties:

navigator.appCodeName is set to the browser code name, which is currently "Mozilla".

navigator.appName is set to the browser name, "BlackBerry."

navigator.appVersion is set to the current browser revision. This takes the form of "4.1.0".

navigator.language is set to the two-letter language code of the default language set on the BlackBerry device.

navigator.mimeTypes is an array of supported MIME types that includes the following properties:

  • navigator.mimeTypes.length
  • navigator.mimeTypes[index]
  • navigator.mimeTypes[index].type
  • navigator.mimeTypes[index].desc
  • navigator.mimeTypes[index].suffixes

The "index" range is 0 to length-1.

"length" is an Integer in the range of 1 through n.

"type", "desc" and "suffixes" are Strings.

The following code fragment demonstrates use:

var numTypes = navigator.mimeTypes.length;
for ( el = 0; el < numTypes; el++ )
{
    document.write("Element " + el + "<br />");
    document.write("MIME Type " +
        navigator.mimeTypes[el].type + "<br />");
    document.write("Description " +
        navigator.mimeTypes[el].desc + "<br />");
    document.write("Suffixes " +
        navigator.mimeTypes[el].suffixes);
    document.write("<p></p>");
}

navigator.platform is set to "BlackBerry"

navigator.plugins is set to an array of installed plug-ins.

navigator.userAgent provides an extract of the user agent from the user-agent header of the HTTP header. This is used by servers to identify the client browser. I tested it with my BlackBerry® 8700 Series handheld with the following result:

Mozilla /4.0 BlackBerry8700/4.2.0 Profile/MIDP-2.0
    Configuration/CLDC-1.1 VendorID/-1

Methods:

 

There are five navigator methods:

Call navigator.javaEnabled() to test if Java is enabled. This always returns true.

navigator.plugins.refresh() has not been implemented. The intent would be to make newly installed plugins available and then update the "plugins" array. When implemented, you would pass true to reload all open documents that contain embedded objects.

Call navigator.preferences() to read BlackBerry device preferences based on the passed parameter. The syntax is preferences(parameter) where the following list details all possible parameters:

general.always_load_images  
security.enable_java returns true
javascript.enabled  
browser.enable_style_sheets  
autoupdate.enabled returns false
network.cookie.cookieBehavior  
network.cookie.warnAboutCookies returns true

navigator.savePreferences() not been implemented.

Call navigator.taintEnabled() to test if data tainting is enabled. Note that this returns false.

If data tainting had been enabled, JavaScript in one window could access properties of another window even when it was loaded from another server. Property values or other data can be tainted (marked) to be either secure or private. If this is done, and if taint has been enabled, then JavaScript cannot pass the tainted values on to any server without the author's permission.


Object: document

 

The document object provides access to elements within an HTML page such as properties of forms, links and colors.

Properties:

 

The following properties are not currently supported:

  • document.anchors

    An array of entries for each anchor in the document.

  • document.applets

    An array of entries for each applet in the document.

  • document.classes

    Creates a Style object used to set the styles of HTML tags with a specific CLASS attribute.

  • document.embeds

    An array of entries for each plug-in in the document.

  • document.ids

    Creates a Style object used to set the style of individual HTML tags.

  • document.images

    An array of entries for each image in the document.

  • document.plugins

    An array of entries for each plug-in in the document.

  • document.tags

    Creates a Style object used to set the styles of HTML tags.

The following are supported properties:

document.alinkColor is a read-only property used to determine the color of links within the current page. Colors are returned as either text values (such as red), or as hexadecimal triplets in RGB format (such as #FF0000). The return format depends on how the link color is represented within the page.

document.bgColor is a read-only property used to determine the background color of the current page. Colors can be returned as text (such as blue) or hexidecimal triplets (such as #0000FF)

document.cookie is used to create or update cookies associated with the current page, or view visible and expired cookies associated with the current page.

To view cookies:

document.write(document.cookie);

To create a cookie:

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+
            (days*24*60*60*1000));
        var expires = ";expires=" +
            date.toGMTString();
    } else var expires = "";
    document.cookie = name + "=" +
        value + expires + ";path=/";
}

document.domain is a read-only property used to determine the domain that served the current page.

document.fgColor is a read-only property used to determine the text color within the current page.

document.formName is used to access and control a specific <form> within the active page. The following code sample shows how to use this property by submitting a form:

document.loginForm.submit();

document.forms is a read-only property that provides access to any <form> object in the active document. Use document.forms.length; to determine the length of the index. Accessing a specific form elements could take the form of document.forms[0].submit();

document.height returns the height of the BlackBerry device screen, in pixels.

Use document.lastModified to extract the date from the HTTP header when the current document was last modified.

document.linkColor provides the color used by the active page to identify hyperlinks. The color is either represented by a text string or the hexidecimal RGB triplet depending on how the page has been coded.

Use document.referrer to get the URL of the referrer through which the user arrived at the current page. This will be set to null if the user arrived at the current page without use of a referrer.

document.title is used to read or set the title of the current page.

document.URL is a read-only property that is set to the URL of the current document.

document.vlinkColor provides the color used by the active page to identify previously visited links.

document.width is set to the width of the BlackBerry device screen, in pixels.

Methods:

 

The following methods are not currently supported:

  • document.captureEvents()

    Sets document to capture all events of the specified type

  • document.contextual()

    Uses contextual selection criteria to set a Style object that can set the style of individual HTML tags.

  • document.getSelection()

    Returns a string set to the text of the current selection.

  • document.handleEvent()

    Invokes the handler for the specified event.

  • document.releaseEvenst()

    Passes a captured event to the normal event hierarchy.

  • document.routeEvent()

    Passes a captured event to the normal event hierarchy.

The following are supported methods:

document.close() closes an output stream and forces data to display.

document.open() opens a stream to collect the output of document.write() or document.writeln() methods.

document.write() writes one or more HTML expressions to a document in the specified window.

document.writeln() writes one or more HTML expressions to a document in the specified window then appends a newline character.

Example:

function doThis() {
    var string1 = "Hi mom!";
    var string2 = "Bye mom!";
    document.open();
    document.write(string1 + "<P>" + string2);
    document.close();
}


Object: form

 

The form object provides access to elements of an HTML form. This object takes the name of the <form> within the current page to access elements from that form. In the following descriptive text, replace the name, "formName" with the name of the <form> that you want to access.

Properties:

 

formName.action is used to either read or set the URL where the <form> will be submitted.

Examples:

var theAction = myForm.action;
myForm.action = "http://www.rim.com/form.php";
myForm.action = "mailto:nospam@rim.com";

formName.elements is used to retrieve a list of elements within the <form>.

Use formName.elements.length or formName.length to determine the size of the list, and formName.elements[index] to access specific elements in the <form>.

Example:

for (el=0; el<myForm.elements.length; el++ )
    document.write(myForm.elements[el]);

formName.method returns the value of the METHOD attribute of the HTML <form> element. This will either be POST or GET. It will be set to the method used to submit the form data to the server.

formName.name returns the NAME attribute of the HTML <form>. This can also be accomplished by using the attribute document.forms[ELEMENT].name.

formName.target returns or sets the target window that <form> responses are sent to after a <form> has been submitted. Setting the target doesn't make a great deal of sense for Blackberry devices because the BlackBerry Browser is a single document interface that never displays more than one browser window at the same time. Therefore, setting the target will have no effect.

Methods:

 

formName.handleEvent() has not been implemented. If it was then the method would invoke the event handler for the specified event.

formName.reset() will reset the default values of any elements in the specified <form>.

formName.submit() will submit the <form> to the server.

Event Handlers:

 

formName.onClick specifies the event that will be triggered when an "on click" event occurs. You can use onClick to determine the current event handler or set the event handler.

Example:

<html>
    <body>
        <script type="text/javascript"
            language="JavaScript">
<!--
// Show field data when button is selected
function showData(){
    var fName = document.myForm.first.value;
    var lName = document.myForm.last.value;
    alert("The name entered is " +
        fName + " " + lName);
}
// -->
        </script>
        <form name="myForm">
            <p>
                Name - First:
                <input type="text" name="first"
                    size="25">
                 Last:
                <input type="text" name="last"
                    size="25">
            </p>
            <p>
                Select button to view entry
                <input type="button" value="isokay"
                    name="showdata" onClick='showData()'>
            </p>
        </form>
    </body>
</html>

The formName.onReset event handler will execute a specified section of JavaScript code when the user resets a form by selecting a Reset button. You can either read or write the setting using this handler.

Complex Example:

<html>
    <body>
        <script type="text/javascript" language="JavaScript">
<!--
// Complex method to display a message when
// the onReset event handler is called
function resetCalled(){
    document.msgForm.message.value =
        "Field data has been cleared";
}
// -->
        </script>
        <form name="dataForm"
            onReset='resetCalled()'>
            <p>
                Field: <input type= "text"
                    name="myField" sizesize="30">
            </p>
            <p>
                <input type="reset" value="Reset"
                    name="Reset"
            </p>
        </form>
        <form name="msgForm">
            <p>
                Status: <input type="text"
                    name="message" size="30">
            </p>
        </form>
    </body>
</html>

Less Complex Example:

<form name="myForm"
    onReset="alert('Defaults restored')">
    Country:
    <p>
        <input type="text" name="country"
            value="USA" size="10">
    </p>
    <p>
        <input type="reset" value="Reset"
            name="doReset">
    </p>
</form>

The formName.onSubmit event handler will execute the specified JavaScript code when the user submits a form.

Example:

<html>
    <body>
        <script type="text/javascript"
            language="JavaScript">
<!--
function isDone() {
    alert("Form has been submitted");
}
// -->
        </script>
        <form name="mainForm" onSubmit='isDone()'>
            <p>
                <b>Suggestions, please!</b>
            </p>
            <p>
                <textarea name="suggest" rows="10"
                    cols="30">
                </textarea>
            </p>
            <p>
                <input type = "submit" value="Submit">
            </p>
        </form>
    </body>
</html>


Object: screen

 

The screen object returns information about the BlackBerry device display such as height, width, color depth and more.

Properties:

 

availHeight provides the screen height in pixels.

availWidth provides the screen width in pixels.

colourDepth provides the bit depth of the color palette. If no palette is used, this will reflect the value of pixelDepth.

height provides the screen height in pixels.

pixelDepth provides the color resolution, in bits per pixel, of the BlackBerry device screen.

width provides the screen width in pixels.


Object: window

 

The window object is automatically created when the BlackBerry Browser parses a <body> or <frame> tag and will return a wide variety of information.

Properties:

 

The following properties are not currently supported:

  • crypto
  • locationbar
  • menubar
  • name
  • opener
  • pageXOffset
  • pageYOffset
  • personalbar
  • screenX
  • screenY
  • scrollbars
  • status
  • statusbar
  • toolbar

The following properties are supported:

window.blackberry is used to access the blackbery object. As previously discussed, window.blackberry.network contains an identifier for the network used by the BlackBerry device, where window.blackberry.location is an object used to get navigational information on GPS-enabled BlackBerry devices.

window.closed always returns false to indicate that the window instance has not been closed.

window.defaultStatus is used to set the default message displayed in the status bar.

The syntax is:

window.defaultStatus = "your message";

window.document provides access to the document object contained within the window. Please refer to the section in this article that describes the document object.

window.frames provides an array of each frame instance created with the <frame> tag within the current document. Array entries can be referenced by index number or the name assigned by the name attribute of the <frame> tag. window.frames.length is used to determine the size of the index.

 


Note: The BlackBerry Browser does not support frames. Instead, a list of frames within the document are displayed for the user to select one frame to open.

 

Example:

// display the name of each frame
for (var el=0; el<=window.frames.length; el++)
    document.write("<p>Frame #" + el + ": " +
        window.frames[el].name + "</p>");

window.history is a core JavaScript object. window.history[index] provides access to an array containing the URLs and names of visited pages. Array entries are referenced by index number, with window.history.length used to determine the size of the index. The URL of the active document is accessed via window.history.current. Use window.history.next to determine the next URL as it relates to the current URL. Use window.history.previous to determine the previous URL in relation to the current URL. There are also three related methods, window.history.back(), window.history.forward() and window.history.go(), will be discussed later in this section.

window.innerHeight and window.innerWidth return the screen height and width respectively in pixels.

window.length returns the number of frames in the parent window. See window.history for more information.

window.location retrieves or sets the URL of the active window.

Example:

<html>
    <head>
        <title>Redirection</title>
    </head>
    <body>
        <script language="JavaScript">
window.location = "http://www.rim.com/";
        </script>
    </body>
</html>

window.offscreenBuffering returns false to indicate that the BlackBerry Browser does not buffer data offscreen before display.

window.outerHeight and window.outerWidth provides the screen height and width in pixels.

window.pageXOffset and window.pageYOffset are both set to zero (0). They reflect the current horizontal and vertical pixel location of the top-left corner of the document within the window.

window.parent provides a reference to the parent window. If no parent window exists then it will point to the current active window.

The syntax to use this is either window.parent.property or window.parent.method where the "property" and "method" is any window object property and method. Note that this is a writable property.

window.screenX and window.screenY both return zero (0).

window.self provides a reference to the current active window. The syntax to use this is either window.self.property or window.self.method where the "property" and "method" is any window object property and method. Note that this is a writable property.

window.top contains a reference to the top window, which is the current window when using a single document interface (SDI) browser such as the BlackBerry Browser. When writing to this property, the syntax is:

window.top.propertyNamewindow.top.methodName

... where propertyName is any property associated with the Window object, and methodName is any method associated with the Window object.

Methods:

 

The following methods are not currently supported:

  • blur()
  • captureEvents()
  • disableExternalCapture()
  • enableExternalCapture()
  • find()
  • focus()
  • handleEvent()
  • moveBy()
  • moveTo()
  • print()
  • releaseEvents()
  • resizeBy()
  • resizeTo()
  • routeEvent()
  • scroll()
  • scrollBy()
  • scrollTo()
  • setHotKeys()
  • setZOptions()

The following methods are supported:

Call window.alert("message") to display a standard alert dialog box. Note that message can be a string or a property of an existing object.

window.atob() and window.btoa() are related methods.

Call window.btoa() to encode potentially problematic data such as data within the ASCII range of 0 through 31 into Base64 format. Afterwards, transmit the encoded data and then use window.atob() to decode it into original form. A simple example is shown below:

// encode passed string into Base64 format
base64Data = btoa("frumious Bandersnatch!'");
// decodeBase64 data into original format
sourceData = atob(base64Data);

Call window.back() to return to the previous URL in the history list.

Call window.clearInterval() to clear the interval that is passed to the method. The passed interval has to be previously defined using the window.setInterval() method. A working example is shown below:

<html>
    <head>
        <script language="JavaScript"
            type="text/javascript">
<!--
var countValue = 1;

// display the count
function displayCount() {
    document.theForm.data.value = countValue++;
}

// stop the count
function endCount() {
    window.clearInterval(intervalID);
}

// set interval to call the display
// function every second
var intervalID = window.setInterval("displayCount()", 1000)
// -->
        </script>
    </head>
    <body onload="displayCount()">
        <form name="theForm">
            <input type="text" size="3" value=""
                name="data">
            <input type="button" value="Stop"
                onclick="endCount()">
        </form>
    </body>
</html>

window.clearTimeout() and window.setTimeout() are related methods.

window.setTimeout() sets a timeout period in milliseconds. The expression or function passed to the method is called after the timeout period elapses. This timeout period can be cleared by calling the clearTimeout() method. A simple example is shown below:

<html>
    <head>
        <script language="JavaScript"
            type="text/javascript">
<!--
// show the time
function showTime() {
    toShow = new Date();
    toShow = toShow.getHours() + ":" +
        toShow.getMinutes() + ":" +
        toShow.getSeconds();
    document.theForm.data.value = toShow;
}

// clear timeout to stop display of the time
function stopTime() {
    window.clearTimeout(timeoutID);
}

// set timeout period to 2 seconds
var timeoutID =
    window.setTimeout("showTime()", 2000);
// -->
        </script>
    </head>
    <body>
        <form name="theForm">
            <input type="text" size="10" value=""
                name="data">
            <input type="button" value="Stop"
                onclick="stopTime()">
            <input type="button" value="Show Time"
                onclick="showTime()">
        </form>
    </body>
</html>

Calling window.close() will return to the previous URL in the history list.

Call window.confirm("message") to display a confirmation dialog box with the "message" passed displayed in the box. The dialog box contains an OK and a Cancel button, and will return true if OK is clicked and false if Cancel is clicked.

Call window.home() to return the user to the default BlackBerry Browser home page.

Call window.open("URL") to open the passed URL in a new window. This method returns the name of the new window. For example:

theWindow = window.open("http://www.rim.com");
window.close(theWindow);

Call window.prompt() to display a prompt dialog box. You must pass a text message to display, and can also pass an optional parameter to set the default value for the user. For example:

<html>
    <body>
        <form>
            <input type="button" value="Prompt"
                onclick="window.prompt('Number:', 25)">
        </form>
    </body>
</html>

Call window.stop() to stop the current download.

 


Please email your comments, suggestions and editorial submissions to