Blackberry Wap-41 Development Guide

Download as pdf or txt
Download as pdf or txt
You are on page 1of 212

BlackBerry Wireless

Handheld Browser
Version 4.1

Content Developer Guide


BlackBerry Wireless Handheld Browser version 4.1 Content Developer Guide

Last modified: 10 November 2005

Part number: SWD_X_CDK-002.002

At the time of publication, this documentation complies with BlackBerry handheld software version 4.1.

©2005 Research In Motion Limited. All Rights Reserved. The BlackBerry and RIM families of related marks, images, and symbols are the
exclusive properties of Research In Motion Limited. RIM, Research In Motion, “Always On, Always Connected”, the “envelope in motion”
symbol, BlackBerry, and BlackBerry Enterprise Server are registered with the U.S. Patent and Trademark Office and may be pending or
registered in other countries.

IBM, Lotus, Domino, and Lotus Notes are trademarks of IBM in the United States. Microsoft is a registered trademark of Microsoft Corporation
in the United States and/or other countries. Microsoft and Windows NT are either registered trademarks or trademarks of Microsoft
Corporation in the United States and/or other countries. Adobe and Photoshop are registered trademarks of Adobe Systems Incorporated in
the United States, and/or other countries. Java and all trademarks and logos that contain Java are trademarks or registered trademarks of Sun
Microsystems, Inc. in the United States and other countries. Mobitex is either a registered trademark or trademark of Telefonaktiebolaget LM
Ericsson Corporation. All other brands, product names, company names, trademarks and service marks are the properties of their respective
owners.

The software referenced in this guide facilitates the creation of content for the BlackBerry Browser. In order to use the software referenced
herein as intended, you must have valid agreements in place with the licensor(s) of the hardware and software referenced in this user guide. In
addition to being required to comply with such license terms, you are strictly prohibited from using the software referenced herein to create,
adapt, or otherwise use in any fashion any content that infringes upon or violates the intellectual property rights of any third-party. The
disclaimer of liability set forth above shall apply with respect to your use of the software in any manner not authorized by Plazmic, Inc.

The BlackBerry device and/or associated software are protected by copyright, international treaties and various patents, including one or more
of the following U.S. patents: 6,278,442; 6,271,605; 6,219,694; 6,075,470; 6,073,318; D445,428; D433,460; D416,256. Other patents are
registered or pending in various countries around the world. Visit www.rim.com/patents.shtml for a list of RIM [as hereinafter defined]
patents.

This document is provided “as is” and Research In Motion Limited and its affiliated companies (“RIM”) assume no responsibility for any
typographical, technical or other inaccuracies in this document. RIM reserves the right to periodically change information that is contained in
this document; however, RIM makes no commitment to provide any such changes, updates, enhancements or other additions to this document
to you in a timely manner or at all. RIM MAKES NO REPRESENTATIONS, WARRANTIES, CONDITIONS OR COVENANTS, EITHER EXPRESS OR
IMPLIED (INCLUDING WITHOUT LIMITATION, ANY EXPRESS OR IMPLIED WARRANTIES OR CONDITIONS OF FITNESS FOR A PARTICULAR
PURPOSE, NON-INFRINGEMENT, MERCHANTABILITY, DURABILITY, TITLE, OR RELATED TO THE PERFORMANCE OR NON-PERFORMANCE OF
ANY SOFTWARE REFERENCED HEREIN OR PERFORMANCE OF ANY SERVICES REFERENCED HEREIN). IN CONNECTION WITH YOUR USE OF
THIS DOCUMENTATION, NEITHER RIM NOR ITS RESPECTIVE DIRECTORS, OFFICERS, EMPLOYEES OR CONSULTANTS SHALL BE LIABLE TO
YOU FOR ANY DAMAGES WHATSOEVER BE THEY DIRECT, ECONOMIC, COMMERCIAL, SPECIAL, CONSEQUENTIAL, INCIDENTAL,
EXEMPLARY OR INDIRECT DAMAGES, EVEN IF RIM HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES, INCLUDING WITHOUT
LIMITATION, LOSS OF BUSINESS REVENUE OR EARNINGS, LOST DATA, DAMAGES CAUSED BY DELAYS, LOST PROFITS, OR A FAILURE TO
REALIZE EXPECTED SAVINGS.

This document might contain references to third party sources of information, hardware or software, products or services and/or third party
web sites (collectively the “Third-Party Information”). RIM does not control, and is not responsible for, any Third-Party Information, including,
without limitation the content, accuracy, copyright compliance, compatibility, performance, trustworthiness, legality, decency, links, or any
other aspect of Third-Party Information. The inclusion of Third-Party Information in this document does not imply endorsement by RIM of the
Third Party Information or the third party in any way. Installation and use of Third Party Information with RIM's products and services may
require one or more patent, trademark or copyright licenses in order to avoid infringement of the intellectual property rights of others. Any
dealings with Third Party Information, including, without limitation, compliance with applicable licenses and terms and conditions, are solely
between you and the third party. You are solely responsible for determining whether such third party licenses are required and are responsible
for acquiring any such licenses relating to Third Party Information. To the extent that such intellectual property licenses may be required, RIM
expressly recommends that you do not install or use Third Party Information until all such applicable licenses have been acquired by you or on
your behalf. Your use of Third Party Information shall be governed by and subject to you agreeing to the terms of the Third Party Information
licenses. Any Third Party Information that is provided with RIM's products and services is provided "as is". RIM makes no representation,
warranty or guarantee whatsoever in relation to the Third Party Information and RIM assumes no liability whatsoever in relation to the Third
Party Information even if RIM has been advised of the possibility of such damages or can anticipate such damages.

This product includes software developed by the Apache Software Foundation (http://www.apache.org/) and/or licensed pursuant to
Apache License, Version 2.0 (http://www.apache.org/licenses/). For more information, see the NOTICE.txt file included with the software.

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and
limitations under the License.

Research In Motion Limited Research In Motion Europe


295 Phillip Street Centrum House, 36 Station Road
Waterloo, ON N2L 3W8 Egham, Surrey TW20 9LF
Canada United Kingdom

Published in Canada
Contents
1 The BlackBerry Wireless Handheld browser...................................................................................................... 9
Using the BalckBerry Wireless Handheld browser ................................................................................................ 9
Browser configurations................................................................................................................................................... 9
WAP Browser configuration................................................................................................................................10
BlackBerry Browser configuration.....................................................................................................................11
Mobile Data ServiceInternet Browser configuration ..................................................................................12
Browser feature support...............................................................................................................................................13
Browser content support..............................................................................................................................................15
Handling multi-part content ..............................................................................................................................17
Determining which markup languages are accepted ................................................................................17
Image conversion ..................................................................................................................................................17

2 Browser interface and features ..........................................................................................................................21


Browser screen.................................................................................................................................................................21
Browser menus........................................................................................................................................................21
WML <do> elements .............................................................................................................................................22
Links............................................................................................................................................................................22
Option lists ...............................................................................................................................................................23
Browser features .............................................................................................................................................................23
History........................................................................................................................................................................23
Cookies.......................................................................................................................................................................23
Cache..........................................................................................................................................................................24
Bookmarks ................................................................................................................................................................24

3 Designing wireless web content.........................................................................................................................27


Creating effective content ...........................................................................................................................................27
Follow basic web design principles ..................................................................................................................27
Organize content effectively...............................................................................................................................27
Select the most appropriate markup language............................................................................................28
Consider BlackBerry device screen sizes .........................................................................................................29
Encourage text entry .............................................................................................................................................29
Minimize download time .....................................................................................................................................29
Improve rendering time........................................................................................................................................29
Creating effective images ............................................................................................................................................29
Defining queues for offline form submission........................................................................................................31
Create an HTTP header property file ...............................................................................................................32
Add queuing parameters directly to the web page....................................................................................33
Making requests for content conditional ...............................................................................................................33
Delivering device-specific content ............................................................................................................................34
Write a browser detection script .......................................................................................................................35
Send handheld-appropriate images.................................................................................................................36

4 Creating XHTML pages.........................................................................................................................................39


Using XHTML-MP ...........................................................................................................................................................39
Creating XHTML-MP–compliant sites..............................................................................................................39
Creating an XHTML-MP page.....................................................................................................................................40

5 Creating WML pages .............................................................................................................................................53


Using WML .......................................................................................................................................................................53
WML design tips .....................................................................................................................................................53
Creating a WML page ...................................................................................................................................................54

6 Testing web pages .................................................................................................................................................65


Using the simulators .....................................................................................................................................................65

7 Creating browser push applications .................................................................................................................67


Push applications ...........................................................................................................................................................67
BlackBerry Browser push support .....................................................................................................................67
WAP Browser push support ................................................................................................................................70
The Mobile Data Service push process ..................................................................................................................71
Central push server ................................................................................................................................................71
Mobile Data Service push applications..................................................................................................................71
Mobile Data Service push application HTTP headers ................................................................................72
Writing Mobile Data Service push applications...................................................................................................74
Writing a RIM push application ........................................................................................................................75
Writing a PAP push application ........................................................................................................................82
Troubleshooting push applications ..........................................................................................................................94

A Extensible Hypertext Markup (XHTML) language reference ......................................................................97


XHTML Mobile Profile reference ..............................................................................................................................97
Structural elements................................................................................................................................................97
Text and text formatting elements...................................................................................................................98
Link elements........................................................................................................................................................101
List elements .........................................................................................................................................................101
Basic form elements ...........................................................................................................................................102
Basic table elements ..........................................................................................................................................104
Image elements ...................................................................................................................................................105
Object elements...................................................................................................................................................106
Meta information ................................................................................................................................................106
Script references...................................................................................................................................................107
WAP CSS reference .....................................................................................................................................................107
Element/CSS property matrix.........................................................................................................................116

B Wireless Markup Language (WML) reference.............................................................................................. 119


WML reference..............................................................................................................................................................119
Structure elements ..............................................................................................................................................119
Text and text formatting elements................................................................................................................120
Link elements........................................................................................................................................................121
Table elements .....................................................................................................................................................121
Image elements ...................................................................................................................................................122
Event elements.....................................................................................................................................................122
Task elements .......................................................................................................................................................124
Input elements .....................................................................................................................................................125
Variable elements................................................................................................................................................126

C JavaScript language reference ........................................................................................................................ 129


Using JavaScript...........................................................................................................................................................129
Supported JavaScript objects...................................................................................................................................129
BlackBerry ..............................................................................................................................................................131
BlackBerry Location ............................................................................................................................................132
Navigator ...............................................................................................................................................................136
Document ..............................................................................................................................................................142
Form.........................................................................................................................................................................150
Screen......................................................................................................................................................................156
Window...................................................................................................................................................................160
D WMLScript language reference ....................................................................................................................... 175
Using WMLScript .........................................................................................................................................................175
WMLScript libraries .....................................................................................................................................................176
Lang .........................................................................................................................................................................176
Dialogs....................................................................................................................................................................180
String .......................................................................................................................................................................181
URL...........................................................................................................................................................................187
Browser ...................................................................................................................................................................193

E Scripting Basics.................................................................................................................................................... 197


Reserved words.............................................................................................................................................................197
Statements.....................................................................................................................................................................198
Operators and expressions .......................................................................................................................................200

Index....................................................................................................................................................................... 205
1
The BlackBerry Wireless Handheld browser
Using the BalckBerry Wireless Handheld browser
Browser configurations
Browser feature support
Browser content support

Using the BalckBerry Wireless Handheld browser


The BlackBerry® Wireless Handheld browser is designed to enable users to access and navigate web pages over a
wireless connection just as they would using a desktop browser. For content developers, however, wireless
browsing poses a number of additional challenges that are not present when designing content for a traditional
desktop environment. Some notable differences include
• Display size: The display sizes of the different BlackBerry devices, while not as small as typical wireless devices,
are still much smaller than a desktop browser.
• Memory: BlackBerry devices have more stringent memory restrictions than desktop computers, which impacts
the amount of data it can store.
• Network: Wireless networks have considerably slower data transfer rates than standard LAN networks. Most
wireless browsers access the Internet through a WAP gateway, which can have size and content limitations.
Research In Motion® (RIM®) has designed two gateways (the Mobile Data Service and the BlackBerry
Internet Service™) to mitigate the impact of the wireless network by supporting a wider range of content and
optimizing it to reduce content sizes and decrease transmission and rendering times.
A different browser configuration is available for each of these gateways. See "Browser configurations" on page 9 for more
information..

This guide provides an overview of the technical aspects browser and outlines design considerations for different
browser configurations.

Browser configurations
BlackBerry devices provide up to three browser configurations:
• WAP Browser: connects to the network using a WAP gateway
• BlackBerry Browser: connects to the network using the Mobile Data Service of the BlackBerry Enterprise
Server®
• Internet Browser: connects to the network using the BlackBerry Internet Service
BlackBerry Wireless Handheld Browser Content Developer Guide

Each browser configuration represents a different setup of the same browser software. The following table
summarizes the characteristics of each configuration:

Configuration Protocol Network Gateway Service books Features


WAP Browser WAP 1.2.2 & WAP-compliant gateway • WAP Transport • WTLS
WAP 2.0 without proprietary WML • WAP Browser • Wireless Session Protocol (WSP) header
extensions (must support WTP- Configuration caching
level segmentation and
reassembly)
BlackBerry Browser HTTP/IPPP BlackBerry Enterprise Server • MDS Transport • HTTP over SSL/TLS, including secure
with the Mobile Data Service • MDS Browser access to corporate intranets, push
Configuration applications, and custom plug-ins for
data parsing and conversion
Internet Browser HTTP/IPPP BlackBerry Internet Service • Internet Transport • hosted equivalent to the BlackBerry
• Internet Browser Enterprise Solution
Configuration • HTTP gateway for network-aware Java™
applications

When a browser configuration is provisioned on the handheld, separate configuration-specific icons appear on the
BlackBerry Home screen. To use a specific browser configuration, a BlackBerry user selects the appropriate icon.
Users can select the configuration that is optimal for the type of content that they are viewing. For example, users
might use the WAP Browser to browse standard Wireless Markup Language (WML) content on the Internet and
use the BlackBerry Browser to access a corporate intranet and view mobile media.
Corporate system administrators can set an IT policy on the BlackBerry Enterprise Server to specify the default
browser that is used for URLs in applications other than the browser, such as in email messages or memos. Users
can also change the default browser. For more information on changing the default browser configuration, see the
on-device help.

WAP Browser configuration


The WAP Browser connects to the network using a WAP gateway. WAP gateways must support WAP Transaction
Protocol-level (WTP) segmentation and reassembly. Proprietary WAP extensions are not supported.1

BlackBerry Wireless WAP gateway Internet Content


Handheld Network (Service Provider Network Servers
Operations Center)

WAP browser connection to the network


The WAP Browser is designed to support WAP 2.0, with the following exceptions:
• no WAP 2.0 provisioning support

1. Research In Motion does not in any way endorse or guarantee the security, compatibility, performance, or trustworthiness of any WAP gateway, and shall have
no liability to you or any third party for issues arising from such WAP gateway.

10
1: Browser configurations

• no vCard support
• no vCalendar support
• limited Wireless Telephony Application Interface (WTAI) support: the browser only supports the Uniform
Resource Identifier (URI) forms of the public WTAI functions
• Limited WAP Cascading Style Sheet (CSS) support
The WAP Browser is designed to use WTLS to access secure WAP services, including WTLS Class 1 (encryption
only, no authentication) and WTLS Class 2 (encryption and server authentication). The WAP Browser configuration
supports the following protocols:
• WAP 1.2.1: The WAP Browser caches WSP headers to decrease the transmission time of requests; it sends
common HTTP headers to the WAP gateway when the WAP connection is first set up, and then sends only
additional or changed headers in each request. In subsequent requests, the WAP Browser sends only headers
that are specific to the request or that contain values that are different from the values that were set up at the
start of the connection.
See the specification WAP-203-WSP-20000504-a at http://www.wapforum.org for more information.
• WAP 2.0: Sends HTTP over Wireless-Profiled TCP (wTCP). The HTTP request is sent to a WAP 2.0 proxy, which
then forwards it on to the server.
The WAP gateway determines which content types are supported. For example, some WAP gateways might
convert HTML content into a series of WML pages, while some might impose a limit on the size of content that the
WAP Browser can request, and so on.

BlackBerry Browser configuration


The BlackBerry Browser is designed to provide corporate customers with secure access to corporate intranets, and
access to the Internet, using the Mobile Data Service of the BlackBerry Enterprise Server. The BlackBerry
Enterprise Server is installed on the corporate network.

Mobile Data Service

BlackBerry Wireless Internet Firewall BlackBerry Corporate Content


Handheld Network Enterprise Server Intranet Servers

BlackBerry Browser connection to the network


The BlackBerry Browser communicates with the connection service using HTTP over the RIM IP Proxy Protocol
(IPPP). Communication between the handheld and the BlackBerry Enterprise Server is encrypted with Triple DES.
In proxy mode, the BlackBerry Enterprise Server sets up the SSL connection on behalf of the handheld.
Communication over the wireless network between the handheld and BlackBerry Enterprise Server is not
encrypted using SSL, but it is still Triple DES-encrypted. Communication over the Internet between the BlackBerry
Enterprise Server and the web server is encrypted using SSL or TLS.

11
BlackBerry Wireless Handheld Browser Content Developer Guide

Mobile Data ServiceInternet Browser configuration


The Internet Browser uses the BlackBerry Internet Service as its gateway to the Internet.
The BlackBerry Internet Service is a component hosted by the BlackBerry Infrastructure. The way in which it
functions is similar to the BlackBerry Enterprise Server Mobile Data Service—for example, both optimize web
content for wireless browsing, and both transcode content types into appropriate formats for display on the
handheld. However, there are a few notable differences:
• The Internet Browsing Service does not require a BlackBerry Enterprise Server, which is typically hosted behind
a corporate firewall. Therefore, it can be made available to non-corporate clients through their BlackBerry
service providers.
• Because users do not access firewalled corporate intranets with the Internet Browser, the need for secure
access does not exist. The Internet Browsing Service, therefore, does not support Triple DES encryption, and
secure sites (HTTPS) are not accessible.

BlackBerry Wireless BlackBerry Internet Content


Handheld Network Infrastructure Servers

Internet Browser connecting to the network


The Internet Browser communicates with the BlackBerry Infrastructure using HTTP over the RIM IP Proxy Protocol
(IPPP). Because the RIM IPPP was designed specifically for the BlackBerry Infrastructure, delivery of HTML is both
faster and more efficient than HTTP over WAP in most current implementations.
Mobile Data ServiceMobile Data Service

12
1: Browser feature support

Browser feature support


Feature Description Browser Configuration
WAP BlackBerry Internet
Content optimization
Browser Session When a user starts a browser session, the Browser Session Management a a
Management system system immediately sends information about the contents of the
browser cache to the Mobile Data Service /BlackBerry Internet Service.
Using this knowledge of the cache contents, Mobile Data Service /
BlackBerry Internet Service can then omit the transfer of any page
component (such as an image, a stylesheet or a JavaScript™ file) that
already exists in the cache (and is still valid). Expired components are
revalidated wherever possible to further attempt to reduce the amount
of data that is transmitted.
Image optimization Depending on handheld capabilities, the Mobile Data Service/Internet a a
Browsing Service converts .jpeg or .gif images to .png images, scales
images to fit the screen dimensions, and reduces color depth.
Content filtering The Mobile Data Service/Internet Browsing Service processes HTML a a
content to remove unsupported tags, converts data to a tokenized
format, and compresses the data for efficient delivery over the wireless
network.
Page rendering The Mobile Data Service and the BlackBerry Internet Service retrieve a a
images while they are processing HTML or XHTML content and include
the images with the pages that they send to the handheld for faster
browsing.
Mobile-friendly browsing
Background downloading Users request a page and download it directly to the messages list. a a a
They can continue to view the current page while the requested page
is downloaded in the background. After the page has been completely
downloaded, users can go to the messages list and select the requested
page to view it.
Offline form submission When the handheld is outside of a wireless coverage area, users can fill a a a
out an HTML form and have the browser queue it for submission to the
server. The browser submits the form as soon as the handheld is in a
wireless coverage area.
Navigation
Soft keys for WML <do> In addition to being added to the browser menu, WML <do> items are a a a
items displayed as “soft keys” in a non-scrolling region at the bottom of the
browser screen.
Trackwheel navigation Using the trackwheel, users can scroll from link to link. Scrolling up or a a a
down moves to the next or previous link on the same line, before
moving to the next line.
When images are placed in <a> or <anchor> tags, users can select the
image to follow the link or to perform the associated action.
One-click support for links To follow a link, users click and hold the trackwheel. a a a
and image-maps

13
BlackBerry Wireless Handheld Browser Content Developer Guide

Feature Description Browser Configuration


WAP BlackBerry Internet
Service provider As with desktop browsers, service providers can provision the handheld a a a
customizable bookmarks browser with custom bookmarks.
Security
Wireless Transport Layer The WAP browser is designed to support WTLS Class 1 (encryption only) a
Security (WTLS) encryption and Class 2 (encryption and server authentication). Both DES (40 and
56-bit) and RC5 encryption (64, 128 and 168-bit) are supported. The
WAP browser does not support the WMLScriptCrypto library.
Triple DES encryption With the Mobile Data Service enabled, browser content is encrypted a
between the Mobile Data Service and the handheld using Triple DES
encryption, the same encryption used when transmitting email
messages.
SSL/TLS encryption With the Mobile Data Service enabled, the BlackBerry Browser a
configuration supports HTTP over SSL or TLS (HTTPS) in one of two
modes:
• proxy mode
• end-to-end mode
Network authentication The WAP Browser configuration supports the Password Authentication a a
Protocol (PAP), which is used for authentication against RADIUS for
Packet Data Protocol (PDP) context activation on GPRS networks. PDP
context activation enables data transmission between the network and
the handheld.
With the Mobile Data Service enabled, the BlackBerry Browser
configuration supports several types of network authentication,
including Basic Authentication, NT LAN Manager (NTLM), and
Kerberos.
Web access restriction To restrict wireless web access, system administrators can enable or a
disable the Mobile Data Service for specific users or user groups.
System administrators can also set specific policies to control which
corporate servers each user can access and which servers can initiate
push connections to the Mobile Data Service.
Usability
On-handheld help A browser Help page is available from the browser menu. a a a
available
Configuration-specific Each configuration of the handheld browser has its own icon on the a a a
icons on the handheld Home screen, which enables users to choose the configuration that is
Home screen optimal for the type of content they are viewing. To use a specific
browser configuration, users click the appropriate icon.

14
1: Browser content support

Browser content support


Content Type Description
Markup languages (See "Determining which markup languages are accepted" on page 17 for more information.)
XHTML Mobile Profile This subset of XHTML 1.1 is defined by the WAP Forum. See
(XHTML-MP) WAP-277-XHTMLMP-20011029-a at http://www.openmobilealliance.org for more information.
WML 1.3 Wireless Markup Language is defined by the WAP Forum. See
WAP-191-WML-20000219-a at http://www.wapforum.org for more information.
HTML Hypertext Markup Language is defined in a W3C specification. The browser ignores tags that are not
present in the XHTML MP subset. Visit http://www.w3.org/TR/html401 for more information on this
specification.
Compact HTML (cHTML) This subset of HTML 2.0, HTML 3.2, and HTML 4.0 is as described in a W3 Consortium Note (NOTE-
compactHTML-19980209). Visit http://www.w3c.org for more information.
WAP CSS Wireless Application Protocol Cascading Style Sheet is defined by the WAP Forum. See
(partial support) WAP-239-WCSS-20011026-a at http://www.wapforum.org for more information.
Images (See “Image conversion” on page 17 for information on converting images.)
WBMP The browser supports monochrome wireless bitmaps. See the Wireless Application Environment Defined
Media Type Specification (WAP-237-WAEMT-20010515-a) at http://www.wapforum.org for more
information on wireless bitmaps.
GIF The handheld supports both the GIF87 and GIF89 image formats. The browser supports animated .gif files.
PNG By default, the browser converts .gif images to .png images. The .png format has a higher compression
ratio and it supports alpha channels.
Java developers can write transcoders to convert other image formats to .png format.
JPEG Only color handhelds support .jpg images directly. With the BlackBerry Browser and Internet Browser
configurations, the Mobile Data Service and BlackBerry Internet Service convert .jpg images for display on
monochrome handhelds.
Mobile media
Media Engine content The browser supports mobile media in the form of PME and PMB files. These formats are binary file formats
that are suitable for transmission to limited footprint wireless handhelds and can be read by the Media
Engine, which is embedded with the handheld browser.
Content developers can author mobile media in several ways:
• using the Plazmic® Composer (available as part of the Plazmic Content Developers Kit for
BlackBerry®) to create PME files. Visit http://www.plazmic.com for more information.
• creating SVG files then converting them to PME files using the Plazmic SVG Transcoder Utility.
Note: The Mobile Data Service and BlackBerry Internet Service can transcode SVG files directly and
send them to the handheld in PME format.
To view mobile media content in a BlackBerry handheld browser, visit http://www.blackberry.com/
demoportal.
Audio The browser allows you to download audio files of up to 128KB in size. The browser supports the following
audio MIME types:
• audio/adpcm
• audio/mid
• audio/midi
• audio/x-midi
• audio/x-oki-adpcm2

15
BlackBerry Wireless Handheld Browser Content Developer Guide

Content Type Description


Scripts
JavaScript The browser supports JavaScript 1.3 and earlier, and subsets of JavaScript 1.4 and 1.5. The browser also
supports the ECMA-262 ECMAScript Language Specification.
Note: JavaScript is only supported on handhelds that are 16MB or greater.
The browser processes JavaScript that is run when the page is first rendered and JavaScript that is
associated with control actions on the page. The JavaScript support handles any additional HTML content
and additional JavaScript content that the JavaScript produces, and reads any auxiliary JavaScript support
libraries that are referenced from the page.
JavaScript support can be enabled or disabled by IT policy or by the user.
Note: The handheld browser does not support stylesheets for Dynamic HTML. As a result, any JavaScript
on the page that creates Dynamic HTML effects (for example, pop-up menus) run but have no visual effect,
and might not be fully functional. The JavaScript support is provided for pages whose HTML content is
partially or fully generated by JavaScript, and for data processing operations coded in JavaScript, such as
input field validation in forms and processing “Login” buttons on various sites.
WML scripts The browser supports WML Script 1.2.1. WML Script enables you to manipulate data values between decks
programmatically. Common operations that are performed in WML Script include input validation, input
aggregation, and conditional form processing.
See WML Script Specification (WAP-193-WMLS-20001025-a) and WML Script Standard Libraries
Specification (WAP-194-WMLSL-20000925-a) at http://www.wapforum.org for more information

Application pushes and downloads


Application pushes Organizations can write push applications that send new web content and alerts to specific users
automatically. With push applications, information can be delivered to the handheld as it becomes
available; users do not have to request or download the data.
For example, instead of relying on users to find intranet content, an organization can transmit data
proactively. Users do not have to connect to corporate servers to check for new content; instead, an alert
can be sent to users when new content is available.
Both the BlackBerry and WAP Browsers support push applications, but support them in different ways.
Push applications are not supported by the Internet Browser configuration.
Wireless application downloads The browser supports the MIDP 2.0 wireless provisioning standard for wireless application downloads.
When an application is downloaded to the handheld, it is automatically installed and the application icon
appears on the Home screen.
Mobile Data Service reliable push With Mobile Data Service reliable push, the browser sends confirmation messages from the handheld for
successful application downloads and pushes.
Customization
APIs for third-party applications. Two APIs assist with third-party integrations with the handheld browser.
• BrowserField API: Third-party applications can use the BrowserField API to embed an HTML, WML, or
PME field anywhere within their application.
• HTTP Filters API: The HTTP Filters API enables code on the handheld (usually third-party application
code) to register itself with the browser as the provider of content from a specified URL. Third-party
developers can then focus on content generation and application logic by creating code that uses the
browser as its UI engine.

16
1: Browser content support

Handling multi-part content


One of the factors that limits the speed with which content can be downloaded and rendered by the handheld
browser is the prevalence of “composite” Web pages (pages composed of a main WML or HTML page and one or
more related auxiliary files, such as style sheets, JavaScript files, or image files). Because each auxiliary file requires
that the browser submit a separate HTTP request, rendering times can be extended considerably.
To improve efficiency, content developers are increasingly posting all the necessary parts of a composite web page
in a single bundle, enabling the browser to download all required content with a single request. The Content-Type
header in the response identifies the content as a multi-part bundle.
The browser supports the following Content-Type values:
• multipart/mixed: Denotes a collection of independent files. The first component of the bundle is assumed to
be the principal file, for example, the WML or HTML page. Subsequent parts are assumed to be the auxiliary
files, such as images, JavaScript files, or style sheets.
• multipart/related: Denotes compound documents, where the document is built from the pieces contained in
the bundle. The browser cannot display the content without all the aggregate components.
• multipart/alternative: Denotes a collection of alternative versions of the same content. The browser searches
until it finds a component with content that it can render.

Determining which markup languages are accepted


Service providers and system administrators can specify whether the browser accepts WML or HTML content, or
both, based on the type of content, the browser configuration, and the gateway behavior. Handheld users can
change this value later. For example, system administrators might want the BlackBerry Browser configuration to
indicate support for both HTML and WML to prevent unwanted content conversions. In other cases, service
providers might want the WAP Browser configuration to indicate preference for WML content so that web sites
with both WML and HTML content send the WML version.
In “HTML only” mode, if a requested URL returns WML content, the web server or gateway returns an HTTP
response of 406 (“Not Acceptable”). The browser then adds the WML capability to the HTTP_ACCEPT header and
requests the URL again.

Image conversion
Note: The image conversion feature requires the BlackBerry Enterprise Server for Microsoft® Exchange version 3.6 or later or the
BlackBerry Enterprise Server for IBM® Lotus® Domino® version 2.2 or later.

The browser includes the following HTTP headers with every request to provide the information that the gateway
needs to convert images so that they can be rendered by the browser:
• Transcode Content (X-RIM-transcode-content) enables image optimization processing by indicating which
image types should be converted.
• User Agent Profile (Profile) contains a URL that includes the following information:
• location of the User Agent Profile (UAPROF) documents on the Internet
• device model number

17
BlackBerry Wireless Handheld Browser Content Developer Guide

• device software version


See the User Agent Profiling Specification (WAP-248-UAProf-20011020-a) at
http://www.wapforum.org for more information.

Image conversion by the Mobile Data Service or BlackBerry Internet Service


The Mobile Data Service and BlackBerry Internet Service use the information in the User Agent Profile document
to determine handheld capabilities, such as screen size, color depth, and accepted image and content types (for
example, only color handhelds can display .jpg images directly).
With this information, the Mobile Data Service and Internet Browsing Service can return handheld-appropriate
content. The HTTPcontenttranscoderslist.property file stores image and content conversion information. By
default, these services convert .jpg images to .png format for display on monochrome handhelds. They also
convert bitmap (.bmp) and .gif files to .png files.

Image conversion by the WAP gateway


With the WAP Browser configuration, images are typically not converted. Most WAP gateways pass all images to
the handheld browser, provided the appropriate image format is listed in the ACCEPT header and the image is
within the allowable size. However, some WAP gateways might restrict the image types or impose size restrictions
that prevent larger image files from being retrieved.

Image processing
The browser loads images differently depending on the gateway that is used.

Gateway Image processing


• BlackBerry Internet Service The Mobile Data Service and BlackBerry Internet Service retrieve images while they
• BlackBerry Enterprise Server for Microsoft process the HTML content, and include images with the HTML content sent to the
Exchange version 3.6 or later handheld. Images appear immediately.
• BlackBerry Enterprise Server for Lotus®
Domino® version 2.2 or later
• WAP gateway The browser first displays image placeholders, with the alternate text of each image (if
• BlackBerry Enterprise Server for Microsoft alternate text is provided). In the background, the browser loads each image separately
Exchange version 3.5 and updates the page as each image becomes available. The browser retrieves images
from the local cache, if possible.

When processing images for display on the handheld, the following techniques apply:
• Horizontal scaling: Images that exceed the screen dimensions are scaled to be no wider than the screen
content area. To maintain the aspect ratio, images are scaled by the same factor in both the horizontal and
vertical dimensions. The screen content area is the screen width minus 5 pixels. The vertical scroll bar that
displays at the right is 5 pixels wide.
• Vertical scaling: Images that are more than twice the screen height are scaled to twice the screen height. To
maintain the aspect ratio, images are scaled by the same factor in the horizontal and vertical dimensions.
Users roll the trackwheel to scroll vertically.
• Size limitation: If a monochrome image is more than 8192 bytes after scaling, the image is discarded. If the
image is part of a link, the browser displays the alternate text for the image.

18
1: Browser content support

• Color: On a monochrome handheld, color images are dithered into a monochrome image. On a color
handheld, the image color depth is reduced to accommodate the number of colors that the device supports.
• Vertical alignment: The vertical alignment in <img> tags is ignored.
The Mobile Data Service and Internet Browsing Service automatically scale and dither images for the BlackBerry
device. With the WAP Browser configuration, the device performs scaling and dithering as necessary.
Note: In the BlackBerry Wireless Handheld software version 3.6 or earlier, the browser displays images in a vertical area that is separate
from the content before and after the image. Images do not appear inline with surrounding text; they are aligned horizontally according
to the ALIGN attribute (ALIGN=LEFT or ALIGN=RIGHT).

19
BlackBerry Wireless Handheld Browser Content Developer Guide

20
2
Browser interface and features
Browser screen
Browser features

Browser screen
By default, the handheld browser is designed to display a non-scrolling title bar at the top of each page that
displays the following items:
• page title
• unread messages
• pending service books
• connection information
• security settings
• network signal strength
When the browser requests or loads pages, a progress bar appears at the bottom of the screen.
On WML pages, <do> elements appear both as soft keys in the non-scrolling section at the bottom of the page
and as menu items on the browser menu. See "Browser menus" on page 21 for more information.
Links to web pages, phone numbers, and email addresses are underlined with a dotted line. See "Links" on page
22 for more information.
When a web page does not fit on one screen, a vertical scroll bar appears on the right side of the screen.

Browser menus
The browser menu provides access to most tasks that users perform when they browse. The menu provides the
standard BlackBerry system menu items, such as Hide Menu and Close, a Help item, and appropriate context
menu items such as Select and Find.
The browser provides standard menu items for navigation, including Home, Back, Forward, History, and Refresh.
The Go To menu item enables users to type any URL.
Specific menu items appear depending on the page and the item that is selected.
BlackBerry Wireless Handheld Browser Content Developer Guide

WML <do> elements


The browser displays WML <do> elements in the following ways:
• as soft keys in the non-scrolling area at the bottom of the screen
• as items on the browser menu
Soft keys provide a familiar way to navigate pages for users who have used WAP browsers on other mobile devices,
such as cellular phones. To select soft keys, users scroll to the soft key and click the trackwheel.

Links
Links are underlined with a dotted line. In BlackBerry handheld software version 3.7 or later, the browser provides
one-click navigation. To follow a selected link, users click and hold the trackwheel or press the Enter key.

Link Type Description


Web page links On a web page, users scroll to links by rolling the trackwheel. Scrolling up or down moves to the next or previous link
on the same line, before moving to the next line.
Image links When images are placed in <a> or <anchor> tags, users can select the image to follow the link or to perform the
associated action. If the size of the image exceeds the screen dimensions, users can click the Full Image menu item to
load the image on a new page. When the Mobile Data Service or the browser encounters a full image request, the image
is retrieved in its original, unscaled form and is transmitted to the browser. The browser renders the image from the top
left. Vertical and horizontal scroll bars are available. To scroll vertically, the user rolls the trackwheel. To scroll
horizontally, the user presses the Alt key and rolls the trackwheel.
Image maps The browser supports image maps. When images contain the image <map> tag, users can select links on portions of an
image. A dotted line around the hot spot denotes a link. To select the link, users click and hold the trackwheel or press
the Enter key.
Phone links The browser supports the following types of phone links:
• Wireless Telephony Application Interface (WTAI) Make Call links (URI form):
<a href="wtai://wp/mc;14165551212">Call office</a>
• telephone links in i-mode format: <a href="tel:14165551212">Call office</a>
• Direct Connect links on iDEN® networks: <a href="dc:234*234*234">Call office</a>
• Computer Telephone Integration (CTI): <a href="cti:333333">Call office</a>
When users click a phone link, the phone opens and a dialog box appears. Users select whether or not to make the call.
Email links The browser supports mailto: links. For example:
<a href="mailto:[email protected]">Email Kate</a>
When users click an email link, the Compose screen appears with a new message.

22
2: Browser features

Option lists
Option lists are displayed as radio buttons (for single-selection lists) or check boxes (for multiple-selection lists). To
select an option in a list, users press the Space key or click the Select Option menu item.
In WML, if a single-selection list does not have an onpick action defined for one of its options, when the user
selects an option, the browser runs either the first <do> action with a type of accept, or, if none have the type
accept, the first <do> action listed.
In HTML and XHTML, options that are grouped in a SELECT tag appear in a drop-down list. To select an option,
users click the drop-down menu and click Change Option.
If a size is defined, the selection list appears in a vertical list instead of a drop-down list.

Browser features
History
The browser maintains a navigation history of up to 20 items. When a user navigates to a page, the URL of that
page is added to the navigation history.
When the history list reaches 20 items, new URLs replace the earliest pages. If memory on the handheld becomes
low, the browser removes history items to free memory.
When the user navigates to a previous page and selects a new link from that page, the browser removes any URLs
after that point in the history. The URL of the newly selected page becomes the next item in the history sequence.
For example, if a user navigates from a music page to a news page, the history displays both pages. If the user
then navigates back to the music page and selects a genre of music, the history displays the music page and the
genre page; the news page is no longer listed.
If a user visits a WML page by some manner other than a predefined link (for example, not a bookmark or the Go To dialog box), or if
that page has a newcontext attribute defined, the browser automatically clears the history before displaying the new URL. This
behaviour is required to conform to WML security specifications.

Cookies
If enabled, the Mobile Data Service or BlackBerry Internet Service store cookies on behalf of the handheld. These
services support cookies based on the RFC 2965 HTTP State Management Mechanism, which supports the HTTP
state management header Set-Cookie-2. See the BlackBerry Enterprise Server Administration Guide for more
information.
Unless these services are configured to do so, the browser stores cookies on its own behalf. The browser supports
standard cookies based on the RFC 2109 HTTP State Management Mechanism, as well as the Netscape® format
for expiry dates (EXPIRES=Weekday, DD-Month-YY HH:MM:SS GMT). The browser maintains cookies when the
device is turned off.

23
BlackBerry Wireless Handheld Browser Content Developer Guide

Cache
The browser stores content in several different caches, depending on the type of data it is. Whenever possible, the
browser loads requested content from the local cache.
Users can clear the content, channel, and cookie caches on the device to free remaining memory and refresh any
visited web pages.

Cache Description
Content This cache includes the raw data cache; it contains all data that is cached as a result of normal browser activity.
Channel This cache contains data that is sent to the handheld by a channel or cache push.
Cookie This cache contains cookies that are assigned to the browser by visited web pages.

The browser respects cache control directives that web servers send in responses, such as Expires, Max-Age, and
Cache-Control. When permitted, the browser retrieves content from the cache based on associated cache control
directives. See the specification WAP-120-UACACH-20010413-a at http://www.wapforum.org for more
information on WAP user agent caching.
On BlackBerry devices, the channel and cookie caches are saved in persistent storage, so information is saved even
if the device is reset. An item is removed from the cache when it expires. If an expiry time is not set explicitly for an
item, the item is removed from the cache after 29 days.
On devices with 8 MB of memory, the content cache is cleared when the user closes the browser. On devices with
16 MB of memory, the content cache persists. The device removes items from the cache to free memory when
necessary, with expired pages removed first.
Service providers can set the size of the raw data cache. The system defaults for the various BlackBerry devices are:
• 200 KB for handhelds with 8MB of memory
• 500 KB for handhelds with 16MB of memory
• 2 MB for handhelds with more than 16MB of memory
Users cannot view or change these options.
Note: The channel and cookie caches are stored persistently; however, information in the content cache is lost if the
handheld is reset or the Mobile Data Service is restarted.

To enable conditional GET requests, content developers must use the following HTTP headers.

Bookmarks
The BlackBerry device browser provides bookmark support that combines the functionality that is typical of
computer-based browsers with added features that are designed specifically for the wireless environment.
As with desktop browsers, users can add bookmarks for any web site that they visit, and they can create a
hierarchy of folders to organize them. Each browser configuration has its own set of bookmark folders, so that
users can organize bookmarks separately based on which browser configuration is best for the bookmarked site.
Bookmark folders for all browser configurations can be accessed regardless of the browser configuration that the
user is browsing with. Users can move or copy bookmarks between any folder. They can edit the title and URL of
bookmarks as necessary, and they can search for and delete specified bookmarks.

24
2: Browser features

During the registration process, service providers can insert a set of customized bookmarks in the browser. These
bookmarks are sent over the wireless network in the browser configuration service record. By default, the
bookmarks are placed in the Bookmarks tree view hierarchy in a new folder called Carrier Bookmarks. The name of
the folder can also be customized.
Frequently used browser pages can also be saved to the Messages screen for quick access.
Bookmarks are useful when users are outside a wireless network coverage area. When users add a bookmark, they
can make the bookmark available offline, which means that both the content and URL of the page are saved.
Offline bookmarks are maintained even if the device is reset.
Offline bookmarks for web pages that contain forms also save the current values of form fields, which users can
use as a template for frequently used forms. For example, users can add an offline bookmark for a page that
contains a form. Later, even if users are outside a wireless network coverage area, they can load the bookmarked
form, fill out the appropriate fields, and submit the form. Users can then save the browser request to the messages
list. When the device returns to a wireless coverage area, the browser sends the request automatically.
Users can back up browser bookmarks using the BlackBerry Desktop Software so that when they update their
devices with new software, their bookmarks are retained.

25
BlackBerry Wireless Handheld Browser Content Developer Guide

26
3
Designing wireless web content
Creating effective content
Creating effective images
Defining queues for offline form submission
Delivering device-specific content

Creating effective content


Many factors (such as the gateway, the browser configuration, and the BlackBerry device memory, screen size, and
color depth) influence how content renders on the device.

Follow basic web design principles


Many standard principles of web site design apply when you create content for wireless devices. Consider the
following design recommendations when you plan your web site:
• Understand your audience: Determine who will use the site and the primary service that your site will provide.
• Create an appropriate site hierarchy: Structure your web site based on its purpose, and organize the site to
minimize the time that it takes users to find information or perform tasks.
• Provide useful links: Minimize the number of pages that users must navigate to accomplish their goals and
consider the following guidelines for links:
• Include a link to the home page on each page.
• Whenever possible, include links to other related pages on your site, to minimize backward navigation
using the browser history.

Organize content effectively


Consider the following guidelines when planning your web site:
• Deliver related content on as few pages as possible: Although a page with more content might take a few
seconds longer to download, users do not have to make subsequent requests, and the information is available
even when users move outside a wireless network coverage area. BlackBerry users can use the trackwheel to
scroll through several screens of text easily.
For example, on WML pages, put related cards in the same deck whenever possible so that the document only
has to be loaded once. If the deck contains a relatively large card that many users might not want to view,
save the card in its own deck to minimize download time.
BlackBerry Wireless Handheld Browser Content Developer Guide

• Add links to related content: If you divide related content into more than one page, make links to related
content easily accessible. Make sure that links to related content are visible in a non-scrolling area of the page
or at the top of the page. For example, you could add a More menu item (or soft key) to enable users to
retrieve related content quickly.

Example of a More link and menu item

Select the most appropriate markup language


When you create a new web site, you must decide whether you are going to write the source in HTML, WML, or
SVG. Consider the following advantages and disadvantages of each markup language when you make your
decision.

Markup HTML/XHTML WML SVG


Advantages • HTML can be migrated to XHTML • most users of wireless web sites are • enables content developers to add
much more easily than to WML accustomed to WML movement and sound to their
• XHTML supports greater layout • currently the most widely used content
versatility than WML markup language for wireless web • offers dynamic layout and
• functionality can be extended applications presentation support.
considerably using JavaScript • has a well-maintained DTD and is • automatically transcoded to PME
• XHTML has greater potential for well-documented and supported format by the BlackBerry MDS
future use, it will become the • functionality can be extended using Optimization Service or BlackBerry
standard for mobile devices WMLScript Internet Service
Disadvantages • usually larger than WML content, so • supports only basic page layout; • SVG is not supported by the
it can take longer to display best suited to very basic sites browser directly; it must be
• few XHTML resources are currently • WMLScript is much less robust than transcoded to PME format (either
available JavaScript by BlackBerry MDS Optimization
Service or BlackBerry Internet
Service, or by the content
developer)
• takes longer to download than
other formats

28
3: Creating effective images

Consider BlackBerry device screen sizes


Design web pages to use the BlackBerry device screen effectively. BlackBerry devices have larger screens than
most other mobile devices, such as mobile phones. Depending on the handheld type and selected font size, the
browser can display 12 to 18 lines of text with 28 to 35 characters on each line. In contrast, many mobile phone
browsers display 4 to 7 lines of text, with 10 to 15 characters on each line.

Encourage text entry


BlackBerry users can use the keyboard to type text into web forms.
The browser supports both <input type="text"> and <textarea> elements in HTML, and
<input type="text"> in WML.

Minimize download time


Download time is affected by three factors: content size, wireless network, and protocol characteristics. For
example, a 15-KB file can take 30 seconds or more to download through a WAP gateway on a GPRS network.
Improve download time by reducing the size of web pages. To reduce the size of web pages, avoid unnecessary
content and images. Reduce image file sizes as much as possible.

Improve rendering time


Rendering on the browser does not affect the time it takes to display content as much as the download time does,
but large content can still require several seconds to parse and display. To improve rendering times, perform the
following actions:
• Create content using WML where possible. WML content typically renders more quickly than HTML or XHTML
content.
• Process and filter content at an intermediate server between the web server and the handheld.
BlackBerry MDS Services and BlackBerry Internet Service will speed up rendering times by processing HTML
content before sending it to the browser. These components filter out unsupported elements and convert
content into a tokenized format that the browser can display efficiently.

Creating effective images


Consider the following guidelines when you include images on your pages:
• Fonts that are saved as images should not be anti-aliased. Anti-aliasing smooths edges by blending the
background and foreground colors. Anti-aliased images do not display optimally on the BlackBerry devices.
• If you resize an image to better fit the smaller screen, when possible, redraw the image. Scaling down the
image results in blurred edges that display poorly.
• Although the BlackBerry MDS Services and BlackBerry Internet Service can dither color images to
monochrome, ideally your images should be saved in monochrome format for display on monochrome
handhelds. The following example demonstrates examples of the same page rendered on a color and

29
BlackBerry Wireless Handheld Browser Content Developer Guide

monochrome handheld. See "Defining queues for offline form submission" on page 31 for more information
on delivering device-appropriate content.

Effect of dithering on color images


• If it is not possible to provide both a color and a monochrome image, verify that the image displays
acceptably on both handheld types.
• Users can specify whether images are loaded or not; therefore, images should not be critical to the
effectiveness and usefulness of your web site.
See "Browser content support" on page 15 for more information on supported image types and image
processing.

Create effective monochrome images


The following examples demonstrate monochrome images that display well on the BlackBerry handheld, and
images that display poorly. The first pair of images display well because they are monochrome and contain well-
defined edges. The second pair of images display poorly because of feathered edges and blurred colors.

Examples of monochrome images that display well in the browser

30
3: Defining queues for offline form submission

Examples of images that display poorly in the browser


To convert an image to monochrome using Adobe® Photoshop®, convert your image to a bitmap using the 50
percent threshold method. You might need to discard any color information by converting the image to grayscale.
The following diagram demonstrates how a gradient appears on the BlackBerry monochrome handhelds.
Gradients appear adequately on the BlackBerry handheld screen, but they are less effective on a smaller scale. For
example, a font with feathered edges appears poorly on the handheld screen.

Examples of grayscale gradients on a BlackBerry monochrome handheld

Defining queues for offline form submission


If you define form-submission queues, BlackBerry users can complete and submit forms and continue browsing
without waiting for the form to be submitted or worrying about whether they are in a wireless coverage area.
Users can load an HTML form (or a WML page with inputs) in the browser, fill in the values, and then submit the
form to an Offline Queues list. The browser continuously processes any queued forms and submits the forms in the
background.
If the device is outside a wireless coverage area, users can still fill in and submit several forms (possibly for
different queues). The browser queues the form requests and submits them when the device is back in coverage.
After forms are submitted, user responses are stored by the browser. Users can open the queue list, and click a
request to view the response.

31
BlackBerry Wireless Handheld Browser Content Developer Guide

The following HTTP headers allow you to create a form queue:

Parameter Required? Description


x-rim-queue-id Yes Specifies the Offline Form Queue to which any GET or POST requests from form submissions on this
page should go. The value may be any text string.
x-rim-next-target No Specifies the next page to load after sending any GET or POST requests resulting from this page to the
Offline Form Queue. The value may be any valid URL.
x-rim-request-title No Specifies the label used to identify this request in the Queue view page. The value may be any text
string. By default, the request is identified using the title of the page.
x-rim-request-id No Specifies whether the browser will generate a unique ID and add it as an HTTP header for every offline
request resulting from this page. The value may be a boolean True or False. By default, this value is True.
x-rim-request-date No Specifies whether the browser will generate a time stamp and add it as an HTTP header for every offline
request resulting from this page. The value may be a boolean True or False. By default, this value is True.

You can creating form queues using these headers either by creating an HTTP property file or by adding the
queuing parameters directly to the HTML or WML page.

Create an HTTP header property file


Creating an HTTP property file in which you define the queuing parameters enables you to create and manage
multiple form queues in a single location. However, it requires that you properly configure your web server to send
the headers when the web page containing the form is requested.
To create a queue for a form on stock-monitor.xhtml, for example, you might define the queuing parameters
as follows:
<Files stock-monitor.xhtml>
Header set cache-control max-age=2592000
Header set x-rim-queue-id Register
Header set x-rim-request-title "Stock Monitor"
Header set x-rim-next-target success.xhtml
</Files>

You can add queuing parameters for additional forms within the same header file.
For a complete sample of the property file, see “Offline form queue header file: .htaccess” on page 32.

Example: Offline form queue header file: .htaccess


<Files stock-monitor.xhtml>
Header set cache-control max-age=2592000
Header set x-rim-queue-id Register
Header set x-rim-request-title "Stock Monitor"
Header set x-rim-next-target success.xhtml
</Files>
<Files stock_monitor.wml>
Header set cache-control max-age=2592000
Header set x-rim-queue-id Register
Header set x-rim-request-title "Stock Monitor"
Header set x-rim-next-target success.wml
</Files>
<Files success.xhtml>

32
3: Making requests for content conditional

Header set cache-control max-age=2592000


</Files>
<Files success.wml>
Header set cache-control max-age=2592000
</Files>

Add queuing parameters directly to the web page


Queuing parameters are handled differently by HTML pages and WML pages.
• In HTML or XHTML, queuing parameters are added using hidden <input> elements:
<input type="hidden" name="x-rim-queue-id" value="Register" />
<input type="hidden" name="x-rim-request-title" value="Stock Monitor" />
<input type="hidden" name="x-rim-next-target" value="success.xhtml" />
To see a sample XHTML page which defines queuing parameters, see“Creating an XHTML-MP page” on
page 36.
• In WML, queuing parameters are added using <postfield> elements:
<input type="hidden" name="x-rim-queue-id" value="Register" />
<input type="hidden" name="x-rim-request-title" value="Stock Monitor" />
<input type="hidden" name="x-rim-next-target" value="success.wml" />
To see a sample XHTML page which defines queuing parameters, see “Creating a WML page” on page 48.

Making requests for content conditional


Download times in a wireless environment are typically slower than on a desktop browser. Therefore, downloading
content that has not changed since it was previously downloaded to the device—and that is therefore already
present in the browser cache—is both unnecessary and a waste of time.
By making GET requests conditional based upon whether the requested content is new you can force the browser
to download content only when the cached content is out of date.
To enable conditional GET requests, content developers must use the following HTTP headers.

Header Description
If-Modified_Since This header is used with a GET method to request that the web server transfer content only if it has been
modified since the specified date and time. For example:
If-Modified-Since: Fri, 6 May 2005 12:00:00 GMT
The request is handled as follows:
• If the requested content has been modified since the specified date, or if the specified date is invalid (such
as a date that is later than the server’s current time), the content will be downloaded as normal.
• If the requested content has not been modified, the server sends a 304 (not Modified) response, and the
browser retrieves the content from the cache.

33
BlackBerry Wireless Handheld Browser Content Developer Guide

Header Description
Last-Modified This header identifies the date and time at which the web content was most recently modified. For example:
Last-Modified: Fri, 6 May 2005 12:00:00 GMT
Note: The exact meaning of this header field depends on the implementation of the origin server and the nature
of the original resource:
• For files, it may be just the file system last-modified time.
• For entities with dynamically included parts, it may be the last-modified time of the most recently modified
component.
• For database gateways, it may be the last-update time stamp of the record.

Delivering device-specific content


When submitting an HTTP request, most desktop browsers, such as Microsoft® Internet Explorer and Netscape
Navigator®, include a header that identifies the browser and version. The BlackBerry device browser includes the
Profile (User Agent Profile) header, which specifies the BlackBerry model and capabilities.
This header is a URL that uses the following form:
http://www.blackberry.net/go/mobile/profiles/uaprof/<BlackBerry-model>/
<software-version>.rdf.
where:
• <BlackBerry-model> is the BlackBerry device model number, for example, 6210 or 7210. The model number
enables you to determine the screen dimensions and the color depth; BlackBerry devices that have a model
number that begins with the number six are monochrome handhelds. Devices that have a model number that
begins with the number seven or eight are color devices.
• <software-version> is the BlackBerry Device Software version, for example, 4.0.0 or 4.1.0.
The information contained in this header enables you to determine the content that is most appropriate for
display on the browser making the request. You can create a script to extract this information, enabling the
content server to return device-appropriate content in the HTTP response.
Note: There is no way to differentiate between HTML or XHTML pages that are designed for desktop browsers and pages
that are designed for wireless devices. The MIME type text/html is used in both cases.

Other headers are also included which help determine what content is sent. For example, the Accept header
specifies the content types that the browser accepts. The preferred content type is determined by the order of
content types in the Accept header, from left to right. For example, the following header indicates that WML is
preferred over HTML, and .gif images are preferred over .png images:
Accept: text/vnd.wap.wml, text/html, image/gif, image/png

Deliver device-specific content


1. Create device- and browser-specific content and images. For design tips, see “Creating effective content” on
page 27.
2. Deploy your content files into browser-specific directories on your web application server.

34
3: Delivering device-specific content

3. Write a browser detection script that parses the Profile header to determine the browser type and the
supported content types, and returns content that is appropriate for the requesting browser. See "Write a
browser detection script" on page 35 for more information.
4. Deploy the browser detection script on your web application server.
5. Test the script by requesting content from a variety of browsers.

Write a browser detection script


Write a browser detection script using any scripting language that enables you to access and manipulate HTTP
headers.
The following example demonstrates how to write a browser detection script using Perl. The complete code
sample is provided at the end of this section. See "Browser detection script (index.pl)" on page 35 for more
information.
1. Assign variables for the Accept and User Agent Profile headers.
$content = $ENV{'HTTP_ACCEPT'};
$browser = $ENV{'HTTP_PROFILE'};;
2. Determine whether the browser accepts HTML content. If it does, parse the User-Agent field to determine
whether this is a BlackBerry device or a standard browser.
if ($content =~ html) {
if ($browser =~ BlackBerry) {
print "Location: http://mobile.blackberry.com/index.html", "\n\n";
}
elsif ($browser =~ Mozilla) {
print "Location: http://www.blackberry.com/index.shtml", "\n\n";
}
}
3. If the browser does not accept HTML, determine whether the client accepts WML content. If it does, parse the
User-Agent field to determine whether this is a BlackBerry device or another type of device.
elsif ($content =~ wml) {
if ($browser =~ BlackBerry) {
print "Location: http://mobile.blackberry.com/wml/index.wml", "\n\n";
}
else {
print "Location: http://www.blackberry.com/unsupported.html", "\n\n";
}
}
4. Provide a default web page for all other browser types.
else
{
print "Location: = http://www.blackberry.com/index.html", "\n\n";
}

Example: Browser detection script (index.pl)

# Copyright (C) 2004 Research In Motion Limited.

35
BlackBerry Wireless Handheld Browser Content Developer Guide

# Note: URLs are used in this example for non-existent web sites.
#!c:\perl\bin\

$content = $ENV{'HTTP_ACCEPT'};
$browser = $ENV{'HTTP_USER_AGENT'};

if ($content =~ html) {
if ($browser =~ BlackBerry) {
print "Location: http://mobile.blackberry.com/index.html", "\n\n";
}
elsif ($browser =~ Mozilla) {
print "Location: http://www.blackberry.com/index.shtml", "\n\n";
}
}
elsif ($content =~ wml) {
if ($browser =~ BlackBerry) {
print "Location: http://mobile.blackberry.com/wml/index.wml", "\n\n";
}
else {
print "Location: http://www.blackberry.com/unsupported.html", "\n\n";
}
}
else {
print "Location: http://www.blackberry.com/index.shtml", "\n\n";
}

Send handheld-appropriate images


This section describes how to write a Microsoft Visual Basic® script that parses the Profile header and returns
device-appropriate images. The complete code sample is provided at the end of this section.
1. Create an Active Server Page.
2. At the top of your content file, specify the script language.
<%@ Language=VBScript %>
3. Specify the content type.
<%
'send the right MIME type
Response.ContentType = "text/vnd.wap.wml"
%>
4. Include the document declaration and markup language tags.
5. Parse the Profile header and determine the handheld model number. You can use the BlackBerry model
number to return a color or monochrome image.
<p><%
' Detect colour devices (model number 7XXX)
uaprof = request.servervariables("HTTP_PROFILE")

6. Specify the format of the Profile header.


' Format is:
‘ http://www.blackberry.com/go/mobile/profiles/uaprof/<model-number>/...

36
3: Delivering device-specific content

7. To accommodate monochrome handhelds by default, specify the BlackBerry 6210 Wireless HandHeld™ as the
default model. By default, the server includes monochrome images in the HTTP response.
model="6210"
8. Include an If statement to verify that a BlackBerry device sent the Profile header.
If ( InStr( uaprof, "http://www.blackberry.com/go/mobile/profiles/uaprof/" ) = 1 )
9. Assign the 4-character string starting at position 53 to the model variable.
Then
model = Mid( uaprof, 53, 4 )
End If
10. Include an If statement to return a color image if the handheld supports color, and a monochrome image if it
supports black and white images only.
if ( model >= 7000 ) Then
Response.write( "<img src=""images/BBLogoClr.gif"" alt=""BlackBerry""/><br/><br/
>" )
Else
Response.write( "<img src=""images/BBlogo.wbmp"" alt=""BlackBerry"" />&nbsp;" )
End If
%>

11. Include the rest of the page content.


Tip: To obtain more BlackBerry device information, perform the following steps:
1. Retrieve the .rdf document that the Profile URL contains.
2. Parse the XML content.
3. Search for an entity in the XML document, for example, “prf:ColorCapable”.

Example: Color handheld detection


# Copyright (C) 2004 Research In Motion Limited.
# Note: URLs are used in this example for non-existent web sites.

<%@ Language=VBScript %>


<%
'send the right MIME type
Response.ContentType = "text/vnd.wap.wml"
%

<p align="center">

<%
' Detect colour devices (model number 7XXX)
uaprof = request.servervariables("HTTP_PROFILE")

' Format is:


‘ http://www.blackberry.com/go/mobile/profiles/uaprof/<model-number>/...
' Set the default model to be the 6210
model="6210"
If ( InStr( uaprof, "http://www.blackberry.com/go/mobile/profiles/uaprof/" ) = 1 )
Then
model = Mid( uaprof, 53, 4 )

37
BlackBerry Wireless Handheld Browser Content Developer Guide

End If

if ( model >= 7000 ) Then


Response.write( "<img src=""images/BBLogoClr.gif"" alt=""BlackBerry""/><br/>
<br/>" )
Else
Response.write( "<img src=""images/BBlogo.wbmp"" alt=""BlackBerry"" />&nbsp;" )
End If

%>

38
4
Creating XHTML pages
Using XHTML-MP
Creating an XHTML-MP page

Using XHTML-MP
XHTML-MP is a subset of XHTML 1.1, extended with some WAP-specific tags. It has been designed for use by
handhelds with smaller displays and limited memory and CPU power. XHTML 1.1 is a superset of HTML 4.0. See
WAP-277-XHTMLMP-20011029-a at http://www.openmobilealliance.org/tech/affiliates/wap for more
information.
The browser ignores any tags that are not part of the XHTML-MP subset and displays content as if the enclosing
tags are not present. See "XHTML Mobile Profile reference" on page 89 for more information.

Creating XHTML-MP–compliant sites


See "Browser content support" on page 12 for more information on browser content and image support.
• Syntax: Although it uses many standard HTML tags, XHTML-MP follows XML syntax conventions. This means
that, unlike HTML, XHTML-MP content must be well-formed.
• Every opening tag—including standalone tags such as <p>, <br>, and <img>—must either have a
corresponding closing tag or be self closing.
• Elements and attributes must be lowercase.
• Attributes must be in quotations.
• Elements must be properly nested so that no element overlaps another element.
• Styles and style sheets: The browser supports both internal and external style sheets, as well as the STYLE
attribute that is used to provide an inline style for specific elements. The <link> tag is used to include
external style sheets, while the <style> tag encloses internal element styles.
The browser supports a limited subset of commonly used properties of the WAP CSS. See "WAP CSS
reference" on page 96 for more information on supported CSS properties.
The browser supports both background colors and background images.
• Fonts: Note the following font limitations:
• Many web clients cannot display fonts other than monospace fonts.
• The browser supports bold and italic fonts, as well as fixed-width fonts. Text that is enclosed in display
tags, such as <strong> and <em>, appears in bold or italic, respectively. Other content-based style tags,
such as <code>, <samp>, and <kbd>, are displayed in a fixed-width font.
BlackBerry Wireless Handheld Browser Content Developer Guide

• Text placed at angles and other text extension elements are not supported. To create text object effects,
consider using SVG for your mobile media content.
• Scripts and events: The BlackBerry device browser supports JavaScript, but does not support applets. The
browser reads the contents of a <script> tag, including any event-handler attributes. Only a limited subset
of event handlers are supported. See "JavaScript language reference" on page 129 for more information.
• Forms: XHTML-MP supports basic forms. The standard keyboard on BlackBerry devices enables users to easily
type text into forms. File and image input types are not supported. Developers who want to create forms for
writing content to the device file system should consider writing a Java application.
The BlackBerry device browser allows you to set up queues so that users can fill out and submit forms even
when they are outside of a wireless coverage area. See "Creating an XHTML-MP page" on page 40 for more
information.
• Tables: The browser supports tables. Users can enable HTML table support to properly display tables that fit
within the screen width of the handheld. Larger tables are split apart with the table cells displayed in vertical
sequence. Tables cannot be nested within each other.
You should test tables thoroughly in the BlackBerry Browser to verify that they display appropriately on the
device.
• Frames: The browser does not support frames (<frameset> or <iframe>) because the complex page layouts
that frames provide are typically not appropriate for the size of BlackBerry device screens.
If a web page contains a frameset, the browser displays a list of the frames in the frameset so that users can
open a selected frame as a standalone page.

Creating an XHTML-MP page


The following sample creates a login page that is XHTML-MP–compliant and appears properly on the BlackBerry
device browser. This sample creates a registration page for a fictitious stock monitoring push service. The page
enables customers of an online broker service to identify a stock that is of interest and set the performance
conditions that must be met for the Stock Monitor service to push out a notification.
To create an XHTML-MP page, complete the procedures that follow in the order in which they appear.
The complete code sample is provided at the end of this section. See "stock-monitor.xhtml" on page 47 for more
information.
Note: In this section, each tag appears on a new line. When content exceeds the length of a line, the content continues on the next
line with an irregular indentation to indicate the line break.

40
4: Creating an XHTML-MP page

The complete sample should resemble the following diagram.

Completed sample, as viewed on a BlackBerry 7780 Wireless Handheld™

Create the skeleton HTML page


1. Create a new XHTML file with the name stock-monitor.xhtml.
2. Include the doctype specification and the <html> and <head> tags for your file.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Mobile 1.0//EN"
"http://www.wapforum.org/DTD/xhtml-mobile10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<base href="http://localhost:8080/">
3. To help users identify their location, include the site name in the title bar.
<title>Stock Monitor -- Registration</title>
4. Close the <head> tag.
</head>

5. Add the opening and closing <body> tags.


<body>
</body>
6. Close the <html> tag.
</html>
Note: The BlackBerry Browser also supports the http-equiv=”refresh” attribute for the <meta> element, which you can use to
redirect one page to another. For example, the following code redirects the browser to BlackBerry/index.html after a 2-second
pause:
<meta http-equiv="refresh" content="2; url=http://localhost:8080/BlackBerry/index.html" />

41
BlackBerry Wireless Handheld Browser Content Developer Guide

Design a navigation bar with links


Tip: An easily accessible navigation bar is an important part of creating an effective web page for BlackBerry handhelds.
Users should be able to access the primary links on each page with minimal scrolling. A bar of links at the top of each page
minimizes scrolling.
1. Design the page navigation by adding links at the top of the page, between the <body> and
</body> elements. In this example, the navigation is nested inside a <div> element so that it can be
formatted using a style sheet.
<div class="navigation">
<a href="index.xhtml">Home</a> |
<a href="symbols.xhtml">Query symbols</a> |
<a href="exchanges.xhtml">Query exchanges</a> |
<a href="monitor-help.xhtml">Help</a>
</div>
2. To emulate the BlackBerry interface separator, add an <hr/> element after the navigation bar. A properly
placed <hr/> tag creates a non-selectable separator line on your page, which makes your web pages
consistent with standard BlackBerry applications.
<hr/>
Tip: For a small screen, use separators to group related information and create a better visual flow for your web
documents.

3. Add instructional text in a <p> tag.


<p>Welcome to Stock Monitor push application. To register, please complete
the form below: </p>
Note: To make sure that the page conforms to XHTML Basic, tags such as <p> must be closed.

Create a form to collect information from the user


1. Under the instructional text, add the form. The following example invokes a .php script when submitted.
<form name="monitor" method="post" action="stock-monitor.php">
</form>
2. Between the <form> and </form> elements, add a two-column table.
<table>
</table>
3. Between the <table> and </table> elements, add a row that contains a input of type “text” for the user’s
email address. Because email addresses can often be long, it should span both columns of the table. The
browser supports the spanning of columns/rows.
<tr>
<td colspan="2">
Type your email address:
<input type="text" name="email" size="40" />
</td>
</tr>
4. Add a row containing the text input for the stock’s trading symbol.
<tr>
<td width="45%">
Product symbol:

42
4: Creating an XHTML-MP page

</td>
<td width="55%">
<input type="text" name="symbol" size="6"/>
</td>
</tr>
5. Add a row containing a drop-down list that enables users to select the exchange on which the stock is listed.
Omit the size attribute of the <select> element to display the radio buttons as a drop-down list instead of
a list box.
<tr>
<td >
Listed on:
</td>
<td>
<select name="exchange">
<option>TSE</option>
<option>NYSE</option>
<option>NASDAQ</option>
<option>Dow Jones</option>
</select>
</td>
</tr>
6. Add a row that contains a group of radio buttons that allow users to choose whether they are notified when
the stock price changes by a specified amount or when the stock price hits a high or low target price.
<tr>
<td>
Notification trigger:
</td>
<td>
<input type="radio" name="notify" value="change" checked>
Target price change
</input><br/>
<input type="radio" name="notify" value="high-low">
Target high/low values
</input>
</td>
</tr>
7. Add a row containing a series of check boxes that enable users to select items that are included in the
notification, such as a chart or news items related to the selected stock.
<tr>
<td>
Include with push:
</td>
<td>
<input type="checkbox" name="chart">Performance chart</input><br/>
<input type="checkbox" name="articles">Related articles</input>
</td>
</tr>
8. Create a submit button and add a reset button to enable users to reset all values to the defaults.
<input type="submit" name="submit" value="Register">
<input type="reset" value=" Reset ">

43
BlackBerry Wireless Handheld Browser Content Developer Guide

9. Add three hidden inputs for user-supplied values. These values are set through a series of JavaScript dialog
boxes.
<input type="hidden" name="change" value="" />
<input type="hidden" name="maxtarget" value="" />
<input type="hidden" name="mintarget" value="" />

Add graphics
Tip: When you create pages to be viewed on wireless devices, avoid using unnecessary images. A recognizable logo is one image you
should include, so that visitors will know that they have arrived at the correct page.

1. Include a right-aligned image using the <img> tag.


<img align="right" src="bb_power-wee.gif" height=20 />

2. Include an alt attribute to provide a short description for the image.


<img align="right" src="bb_power-wee.gif" height=20
alt="powered by BlackBerry" />

3. Make the image a link by nesting it in an <a> element.


<a href="www.blackberry.com">
<img align="right" src="bb_power-wee.gif" height=20
alt="powered by BlackBerry" />
</a>

Create a footer with email and phone links


1. To create a footer that resembles the header, include the footer elements in a <div> tag, with the same
navigation CLASS attribute that is used for the header navigation. The sample separates the footer with
preceding and following <hr/> tags.
<hr/>
<div class=”navigation”>

</div>
<hr/>
2. Add an email link to your page.
<a href="mailto:[email protected]">Email</a>
3. Add a phone link to your page.
<a href="tel:416-555-0000">Telephone</a>

Add styles
1. Create styles using WAP CSS syntax. These styles can be nested under a <style> element that is located
between the <head> and </head> elements or included in a separate CSS file.
div.navigation {
background-color: lightgrey;
font-family: arial;
font-size: 4pt;
}

44
4: Creating an XHTML-MP page

2. If you have created an external style sheet, between the <head> and </head> elements, add a <link>
element. This element must have attributes that define the name of the CSS file and identify the content as
style properties.
<link rel="stylesheet" href="stock-monitor.css" type="text/css" />

The complete CSS file is provided at the end of this section. See "stock-monitor.css" on page 50 for more
information.

Add JavaScript(s) to extend functionality


Note: The sample code uses an internal JavaScript to ensure that the form is not submitted with empty input fields. It also uses prompt
dialogs to acquire additional information from the user based on their choices in the form.

1. Between the <head> and </head> elements, add a <script> element and define the script language as
JavaScript.
<script type = "text/javascript">
</script>
2. Between the <script> and </script> elements, define a function called ValidateForm().
function ValidateForm() {
3. Add a routine to verify that the user has specified an email address. If no email address has been specified,
display a dialog box.
if ((emailID.value==null)||(emailID.value=="")) {
alert("Please Enter your Email Address");
emailID.focus();
return false;
}
4. Add a routine to verify that the user has specified a stock symbol. If no stock symbol has been specified,
display a dialog box.
if ((symbol.value==null) || (symbol.value=="")) {
alert("Please enter a symbol for the financial product you want
to monitor.");
symbol.focus();
return false;
}
5. Add a routine to determine if the user selected the Target change value notification trigger. If so, display a
dialog box that enables the user to specify the amount by which the stock price must change to trigger a
notification.
if(document.monitor.notify[0].checked) {
change = prompt("Specify the value change for " + symbol.value +
" required to trigger a notification: ", change);
if (confirm("You will be notified when " + symbol.value + " changes by
at least $" + change + " per share, based on it's value
at the time ofregistration")==true) {
document.monitor.change.value = change;
return true;
} else {
return false;
}

45
BlackBerry Wireless Handheld Browser Content Developer Guide

}
6. Add a routine to determine if the user selected the Target high/low value notification trigger. If the user
has selected the check box, display a dialog box that enables the user to specify a target high followed by a
dialog box that enables the user to specify a target low.
if(document.monitor.notify[1].checked) {
maxtarget = prompt("Please enter the target high value for " +
symbol.value + ":", maxtarget);
mintarget = prompt("High value set at $" + maxtarget + ". Please
enter the target low value:", mintarget);
if (confirm("You will be notified when the financial product " +
symbol.value + " reaches a high of $" + maxtarget + " or
a low of $" + mintarget + " per share.")==true) {
document.monitor.maxtarget.value = maxtarget;
document.monitor.mintarget.value = mintarget;
return true;
} else {
return false;
}
}
7. Add an onSubmit event handler to the <form> element, which calls the ValidateForm() JavaScript function
created in step 1.
<form name="monitor" method="post" action="bb-broker.php" onSubmit="return
ValidateForm()">

Set up a queue for offline form submissions


In the sample, offline form submission is set up adding hidden <input> elements to the form.

> Between the <form> and </form> elements, add a hidden <input> element for each header that you want
to define. The x-rim-request-title property must be defined; other queuing parameters are optional.
For each <input> element, the name attribute corresponds to the header name (for example,
x-rim-queue-id), while the value attribute defines the value for that header.
<input type="hidden" name="x-rim-queue-id" value="Register" />
<input type="hidden" name="x-rim-request-title" value="Stock Monitor
Registration" />
<input type="hidden" name="x-rim-next-target" value="success.html" />

See "Defining queues for offline form submission" on page 27 for more information about the headers that
are used to define form queues.
Tip: You can also set up forms by formatting your web site with the necessary headers. See "Defining queues for
offline form submission" on page 27 for more information.

Test the page


When you design content for the browser, you should test content in the BlackBerry device browser throughout
the design and creation process to verify that the page displays and functions properly on BlackBerry devices. If
you wait until the page is complete before you test it, errors can be more difficult to correct.

46
4: Creating an XHTML-MP page

Test content using a BlackBerry device or by using the BlackBerry device simulator. The BlackBerry device
simulator is included with the BlackBerry Java Development Environment (JDE) and the Plazmic Content
Developer Kit (CDK). The simulator’s browser application includes a built-in WAP gateway, so that you can test
WML pages by opening them in the browser. See "Testing web pages" on page 65 for more information.

Example: stock-monitor.xhtml

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML Mobile 1.0//EN"


"http://www.wapforum.org/DTD/xhtml-mobile10.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">


<head>
<title>Stock Monitor -- Registration</title>

<!-- Adding a meta tag define how this page may be cached. -->
<meta http-equiv="cache-control" content="public" />

<!-- Linking to an external stylsheet. -->


<link rel="stylesheet" href="stock-monitor.css" type="text/css" />

<!-- Creating a javascript which checks input and selections, and requests
further information through dialogs. -->
<script type = "text/javascript">

function ValidateForm() {

<!-- set variables -->


var emailID=document.monitor.email;
var symbol=document.monitor.symbol;
var change=””;
var targetmax=””;
var targetmin=””;

<!-- If no email address has been entered, alert user. -->


if ((emailID.value==null)||(emailID.value=="")) {
alert("Please Enter your Email Address");
emailID.focus();
return false;
}

<!-- If no symbol has been entered, alert user. -->


if ((symbol.value==null) || (symbol.value=="")) {
alert("Please enter a symbol for the financial product you want
to monitor.");
symbol.focus();
return false;
}

<!-- If target price change used, get change amount. -->


if(document.monitor.notify[0].checked) {
change = prompt("Specify the price change for " + symbol.value
+ " required to trigger a notification: ",
change);
if (confirm("You will be notified when " + symbol.value +

47
BlackBerry Wireless Handheld Browser Content Developer Guide

" changes by at least $" + change + " per


share, based on it's value at the time of
registration.")==true) {
document.monitor.change.value = change;
return true;
}
}

<!-- If target max/min values used, get them. -->


if(document.monitor.notify[1].checked) {
maxtarget = prompt("Please enter the target high value for " +
symbol.value + ":", maxtarget);
mintarget = prompt("High value set at $" + maxtarget + ". Please
enter the target low value:", mintarget);
if (confirm("You will be notified when the financial product "
+ Symbol.value + " reaches a high of $"
+ maxtarget + " or a low of $" + mintarget
+ " per share.")==true) {
document.monitor.maxtarget.value = maxtarget;
document.monitor.mintarget.value = mintarget;
return true;
} else {
}

}
</script>

</head>

<body>

<!-- Creating a navigation bar. -->


<div class="navigation">
<a href="index.xhtml">Home</a> |
<a href="symbols.xhtml">Query symbols</a> |
<a href="exchanges.xhtml">Query exchanges</a> |
<a href="monitor-help.xhtml">Help</a>
</div>
<hr/>

<p>Welcome to Stock Monitor push application. To register, please complete


the form below: </p>

<!-- Creating a form to collect information. -->


<form name="monitor" method="post" action="stock-monitor.php"
onSubmit="return ValidateForm()">
<hr/>
<!-- Adding a table to organize form elements. -->
<table>
<tr>
<td colspan="2">
Enter your email address:
<input type="text" name="email" size="40" />
</td>
</tr>
<tr>
<td width="45%">
Product symbol:

48
4: Creating an XHTML-MP page

</td>
<td width="55%">
<input type="text" name="symbol" size="6"/>
</td>
</tr>
<tr>
<td >
Listed on:
</td>
<td>

<!-- Creating a drop-down list. -->


<select name="exchange">
<option>TSE</option>
<option>NYSE</option>
<option>NASDAQ</option>
<option>Dow Jones</option>
</select>
</td>
</tr>
<tr>
<td>
Notification trigger:
</td>
<td>

<!-- Creating a group of radio buttons. -->


<input type="radio" name="notify" value="change" checked>
Target price change
</input><br/>
<input type="radio" name="notify" value="high-low">
Target high/low value
</input>
</td>
</tr>
<tr>
<td>
Include with push:
</td>
<td>
<!-- Creating a series of checkboxes -->
<input type="checkbox" name="chart">
Performance chart
</input><br/>
<input type="checkbox" name="articles">
Related articles
</input>
</td>
</tr>
</table>
<hr/>
<!-- Adding submit and reset buttons. -->
<center>
<input type="submit" name="submit" value="Register" />
<input type="reset" value="Reset" />
</center>

49
BlackBerry Wireless Handheld Browser Content Developer Guide

<!-- Adding some hidden inputs that will be set via the ValidateForm()
javascript function. -->
<input type="hidden" name="change" value="" />
<input type="hidden" name="maxtarget" value="" />
<input type="hidden" name="mintarget" value="" />

<!-- Adding some hidden inputs that define the queue for the offline
submission of the form. -->
<input type="hidden" name="x-rim-queue-id" value="Register" />
<input type="hidden" name="x-rim-request-title" value="Stock Monitor
Registration" />
<input type="hidden" name="x-rim-next-target" value="success.html" />

</form>

<!-- Adding an image with a link. -->


<a href="www.blackberry.com">
<img align="right" src="bb_logo.gif" height=20 alt="BlackBerry" />
</a>

<!-- Adding footer with non-browser links. -->


<hr/>
<div class="navigation">
Contact Stock Monitor:
<a href="mailto:[email protected]">Email</a> |
<a href="tel:416-555-0000">Telephone</a>
</div>
<hr/>

</body>
</html>

Example: stock-monitor.css
p {
font-family: arial;
font-size: 6pt;
colour: black
}
table {
background-color: lightgrey;
font-family: arial;
font-size: 6pt;
}
input {
-wap-input-required: true;
font-family: arial;
font-size: 6pt;
}
select {
font-family: arial;
font-size: 6pt;
border-width= 0pt;
}
div.navigation {
background-color: lightgrey;

50
4: Creating an XHTML-MP page

font-family: arial;
font-size: 4pt;
}
a {
color: darkblue
}

51
BlackBerry Wireless Handheld Browser Content Developer Guide

52
5
Creating WML pages
Using WML
Creating a WML page

Using WML
WML is an XML language that conforms to XML 1.0 rules; for example, tags are case-sensitive, and every opening
tag must either have a corresponding closing tag or be self closing. The browser supports WML 1.3 and WML
Script 1.2.1. See "Wireless Markup Language (WML) reference" on page 119 for more information on supported
WML tags.
Note: The browser supports WML Script except for the Float standard library and all functions that use floating point values. Floating
point refers to numbers with varying number of digits before or after the decimal point; that is, the decimal point can float.

WML is primarily a text-based language that facilitates chunking information into small sections for display on
mobile devices. Because of the small screen size, typical desk-top-oriented HTML pages do not typically display
effectively on a mobile browser. HTML content is generally designed for a much larger space, and it often includes
elements such as complex tables or framesets that render poorly or not at all on the handheld browser. Also, the
amount of text on most HTML sites results in a browsing experience that requires a great deal of scrolling.
WML breaks down information into chunks, called “cards.” Each card contains a single topic, or about a screen’s
worth of content. These related WML cards are then connected using navigational links. A set of related WML
cards are included in a single .wml file, which is referred to as a “deck.” From an HTML perspective, it is similar to
creating a single HTML file that includes multiple <body> sections.
WML offers several advantages for mobile browsers:
• WML decks reduce the number of client-server transactions; decks are transmitted as individual pages.
• WML cards provide an optimal device browsing experience because chunks of content display as a single
screen and they require minimal scrolling.
• WML has a small tagset compared to HTML.
• WML supports forms, option lists, and text entry, which is ideal for users who want to retrieve specific
information.

WML design tips


• Limit one element for each line of code.
• Syntax: Use proper syntax. WML is an XML language; therefore, content must be well-formed.
• Every opening tag—including standalone tags such as <p>, <br>, and <img>—must either have a
corresponding closing tag or be self-closing.
BlackBerry Wireless Handheld Browser Content Developer Guide

• Elements and attributes must be lowercase.


• Attributes must be in quotations.
• Elements must be properly nested such that no element overlaps another element.
• File types: Verify that your application server accepts .wml files, plus any other file types (for example .gif, .pl)
that might be included in your content. Application servers include a list of supported file and application
types, known as Multipurpose Internet Mail Extensions (MIME) types.
• WML-specific elements: While the WML tagset is essentially a subset of HTML, several elements are unique to
WML.
• <do> elements: WML <do> elements are triggered by user-initiated events. Each <do> element has a
corresponding action that occurs when the user performs a <do> event.
In the browser, <do> elements that are defined on a card appear both as menu items on the browser
menu and as “soft keys" in a non-scrolling area at the bottom of the screen.
If a label attribute is included in the <do> element, the label text is displayed as the menu item and the
soft key. If no label is included, a default label is displayed based on the type of <do> element, such as
Accept, Prev, Help, Reset, Options, Delete.
• <select> elements: WML <select> items are displayed either as a list of radio buttons (for single
selection) or as a list of check boxes (for multiple selection). Users can use the trackwheel or keyboard to
scroll through the options, and then click the Select Option menu item or press the Space key to select an
option.
You can use the onpick attribute to perform an action when the user selects an option. See "Use WML
events" on page 57 for more information.
• <access> elements: WML <access> items limit which other web pages can reference your pages. To
grant an authorized domain access to your page, (for example, www.blackberry.com), provide the domain
attribute.
<head>
<access domain="255.255.255.255"/>
</head>
When a user attempts to access the page from another domain, the “Access denied” message appears.
Note: Specifying deck access limits users’ ability to open your web site in a browser. Unless your browser application is designed
for a private audience (such as an intranet application), do not use the <access> element.

Creating a WML page


The following example demonstrates how to create a simple login page in WML and provides some tips about how
to create a page that displays successfully on the browser.
The following sections walk through the steps required to create a sample WML deck. In this example a deck is
created that contains three cards: a login screen, a links screen, and a help screen to assist users who are having
trouble logging in. The complete WML sample is provided at the end of this section. See "login.wml" on page 60
for more information.

54
5: Creating a WML page

Define the WML deck and cards


1. Create a file with the name stock-monitor.wml.
2. Define your document.
<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN"
"http://www.wapforum.org/DTD/wml_1.1.xml">
3. Insert the opening WML element tag. All templates and cards are added between this tag and its closing tag.
<wml>
4. Create the main card that users will use to log in. This card also functions as the Home page of the site.
<card id="Page1" title="Stock Monitor Registration">
5. Specify a default <do> action for the card. <do> elements with the type="accept" attribute are the default
card action and they appear first on the browser menu.
<do type="accept" label="Next">
Provide a descriptive label for each <do> action. Limit the length of <do> labels to 12 characters so that the
label does not exceed the width of the browser menu. Capitalize the first letter of each word in a label to
maintain consistency with BlackBerry menu items. This page enables users to continue to the next card in the
deck, so it is labelled “Next.”
All <do> elements require a corresponding action, for example, <go> or <prev>. A subsequent procedure adds
an action to this element.
6. Add the closing tag for this card.
</card>
7. Create additional cards with Next and Back soft keys. This card contains an option list of links.
<card id="Page2" title="Stock Monitor -- Choose Stock">
<do type="accept" label="Next">
<go href="#Page3" />
</do>
<do type="accept" label="Back">
<go href="#Page1" />
</do>
</card>
8. Create a new card for the help page.
<card id="Help" title="Help">
<p>
This page contains helpful hints.
</p>
</card>
9. Add the closing tag for this deck.
</wml>

Add a template
WML templates enable you to include content in several cards at the same time. Using templates saves time and
minimizes the content that is sent over the wireless network; content that is duplicated across multiple cards only
needs to be included once in the deck. Templates can only contain <do> and <onevent> tags.

55
BlackBerry Wireless Handheld Browser Content Developer Guide

In this example, we want to add a help menu item that is available for each card.
1. Create the template by inserting the following tag immediately following the <wml> tag:
<template>
2. Add the repeated content or functionality. To add a Help menu item, add a <do> element that contains a
<go> action that identifies the help page to be displayed:

<do type="help" label="Help" >


<go href="#help"/>
</do>
Notes: To create a link to a subsidiary card, prefix the card id with a number sign (#) character.
WML <do> elements appear at the bottom of the screen from left to right. The order in which the items appear depends on the
sequence of <do> elements in the file; the first <do> element appears at the left.

3. Close the <template> element:


</template>
The Help soft key is added by default to every card in the deck. Because most cards in the deck contain Next
and Back soft keys, however, the Help option will only appear as menu item.
See "Use WML events" on page 57 for more information on overriding template content on specific cards.

Add input fields


1. Add an email input field to the first card. WML does not require that you enclose <input> elements in a
<form>.
<p>
Please enter your email address:
<input type="text" name="email" />
</p>
Note: The browser hides user input for fields in which you specify type="password".

By default, input fields begin on a new line. Text fields span the width of the browser window. To limit the
number of characters that users can type, use the maxlength attribute.
2. Add an stock symbol input field to the second card.
<p>
Product trading symbol: <input type="text" name="symbol"
format ="*AAA" />
</p>
3. To specify the action that the card performs when the user submits the content, add a <go> tag inside the
primary <do> element that you created in the “Define the WML deck and cards” procedure. In this example, a
Perl script runs. In the following code, the <do> element exists already.
<do type="accept" label="Submit">
<go href="/cgi-bin/loginScript.pl" method="post">
<postfield name="name" value="$(loginID)"/>
<postfield name="password" value="$(password)"/>
</go>

56
5: Creating a WML page

</do>
Using the <do> element, instead of <a> and <anchor> tags enables you to bind an action to the default
option for the page.

Create an option list


1. Add introductory text to the Page2 card.
<p>
Listed on:
</p>
2. Add an option list using the <select> element.
<select name="name" title="Listed on" value="TSE">
<option value="TSE">TSE</option>
<option value="NYSE">NYSE</option>
<option value="NASDAQ">NSADAQ</option>
<option value="Dow Jones">Dow Jones</option>
</select>
Note: This section adds a single-selection option list. In the <select> element, that is, a set of radio buttons. To render a list as
a series of check boxes, add the attribute multiple="true" to the <select> element.

3. On the Page3 card, add two more option list. One will enable users to specify the notification trigger method,
the other will enable them to select what additional information will be pushed with the notification. The
second list is a multiple-selection list.
<p>
Notification trigger:
<select name="trigger" value="c">
<option value="c">Target price change</option>
<option value="r">Target high and low values</option>
</select>
</p>
<br/>
<p>
Include with push:
<select name="includes" multiple="true">
<option value="chart">Performance chart</option>
<option value="articles">Related articles</option>
</select>
</p>

Add an image
Use the <img> tag to include an image on the Help page. Place the image right-aligned in a new paragraph after
the Help page contents.
<p align="right" >
<!-- Adding an image with a link. -->
<a href="www.blackberry.com">
<img src="bb_power-wee.gif" height=20 alt="BlackBerry" />
</a>
</p>

Use WML events


This section describes how to use WML events. You can use the following WML events:

57
BlackBerry Wireless Handheld Browser Content Developer Guide

• User-initiated events trigger actions when the user interacts with a screen element. You can use the following
events:
• onenterbackward: triggers an action to occur when the user enters the card by clicking <prev>
• onenterforward: triggers an action to occur when the user enters the card by clicking <go>
• onpick: triggers an action to occur when the user selects an option
• Timeline events trigger actions that occur at a certain point in time. A single event is available:
• ontimer: triggers an action to occur when the timer on a card expires

1. On the Help card, add an onpick event attribute to each option in the options list, so that the browser opens
the specified URL when the user selects the option.
<option value="rim" onpick="http://www.rim.com">
Research In Motion
</option>
<option value="blackberry" onpick="http://www.blackberry.com">
BlackBerry products
</option>
<option value="developers" onpick="http://www.blackberry.com">
BlackBerry Developer Zone
</option>
2. Modify the <card> element for the first card (Page1) to add a timer event, so that the Help card opens if the
user takes longer than 2 minutes to log in.
<card id="main" title="BlackBerry WML sample" ontimer="#help">
<timer value="2400"/>
Use the WML ontimer attribute to force new content to the browser after a specified amount of time has
passed.
The timer value is measured in tenths of a second, and the counter is reset when the page is refreshed. The
<timer> element is commonly used to redirect a WML page to another WML page; setting the value
attribute to 1 redirects the page automatically.

Add WMLScript(s) to extend functionality


1. Create a file with the name stock-monitor.wmls.
2. Define a function called setTriggers().
function setTriggers() {
3. Declare variables for each trigger. Two variables must be declared for the target high/low option, because two
values will be required. Set each variable to an initial value of null.
var valChange = "";
var valHigh = "":
var valLow = "";
4. Retrieve the trigger variable from the Page3 card.
var trigger = WMLBrowser.getVar("trigger");
5. Determine which trigger option was selected.
var change = String.find(trigger,"c");
var range = String.find(trigger,"r");

58
5: Creating a WML page

6. If the Target price change option was selected, display a dialog box that enables the user to specify the
amount by which the stock price must change to trigger a notification.
if(change) {
var valChange = Dialogs.prompt("Change value: ","");
var message = "You will be notified when the value changes by $"
+ valChange;
}
7. If the Target high/low value option was selected, display a dialog box that enables the user to specify a
target high, followed by a dialog box that enables the user to specify a target low.
if(range) {
var valHigh = Dialogs.prompt("High value: "."");
var valLow = Dialogs.prompt("Low value: ", "");
var message = "You will be notified when the value reaches a high of $"
+ valHigh + " or a low of $" + valLow;
}
8. Add a go event to the Page3 card that calls the setTriggers WMLScript function created in step 1.
<do type="accept" label="Next">
<go href="stock-monitor.wmls#setTriggers()"/>
</do>

Set up a queue for offline submissions


> Between the <go> and </go> elements, add a <postfield> element for each header that you want to define.
The x-rim-request-title property must be defined; other queuing parameters are optional.
For each <input> element, the name attribute corresponds to the header name (for example,
x-rim-queue-id), while the value attribute defines the value for that header.
<postfield name="x-rim-queue-id" value="Login"/>
<postfield name="x-rim-request-title" value="Login"/>
<postfield name="x-rim-next-target" value="success.wml"/>
See "Defining queues for offline form submission" on page 27 for more information about the headers used
to define form queues.
Note: You can also set up forms by formatting your web site with the necessary headers. See "Defining queues for offline form
submission" on page 27 for more information.

Override a template
You might not want template elements to appear on every card in the deck. Use a technique called shadowing to
disable certain template elements on a card by adding the <noop> element. For example, you can disable the link
to the Help card on the Help card itself. To use the <noop> element to disable a soft key, first add the <do>
element that you want to deactivate, and then add the <noop> element.
1. On the Help card, after the <card> element, add the <do> element with the label="Help" attribute from
the template that you want to shadow.
<do type="help" label="Help" >
2. Instead of including the <go> element within the <do> element, use the <noop/> element. <noop/> tells the
browser to disable this option for this card.
<noop/>

59
BlackBerry Wireless Handheld Browser Content Developer Guide

</do>

Test the page


When you design content for the browser, you should test content in the BlackBerry device browser throughout
the design and creation process to verify that the page displays and functions properly on the handheld. If you
wait until the page is complete before you test it, errors can be more difficult to correct.
Test content using a BlackBerry device or by using the BlackBerry device simulator. The simulator is included with
the BlackBerry Java Development Environment (JDE) and the Plazmic Content Developer Kit (CDK). The
simulator’s browser application includes a built-in WAP gateway, so that you can test WML pages by opening
them in the browser. See "Testing web pages" on page 65 for more information.

Example: login.wml

<?xml version="1.0"?>
<!DOCTYPE wml PUBLIC "-//WAPFORUM//DTD WML 1.1//EN" "http://www.wapforum.org/DTD/
wml_1.1.xml">

<!--Copyright (C) 2004 Research In Motion Limited. All Rights Reserved -->
<!--loginScript.pl script, referenced in this example, is not shown here -->

<wml>

<template>
<do type="help" label="Help">
<go href="#Help"/>
</do>
</template>

<card id="Page1" title="Stock Monitor Registration" ontimer="#Help">


<timer value="2400"/>
<do type="accept" label="Next">
<go href="#Page2" />
</do>

<p>
Please enter your email address:
<input type="text" name="email" />
</p>
<p align="right" >
<!-- Adding an image with a link. -->
<a href="www.blackberry.com">
<img src="bb_power-wee.gif" height=20 alt="BlackBerry" />
</a>
</p>
</card>

<card id="Page2" title="Stock Monitor -- Choose Stock">


<do type="accept" label="Next">
<go href="#Page3" />
</do>
<do type="accept" label="Back">
<go href="#Page1" />
</do>

60
5: Creating a WML page

<p>
Product trading symbol: <input type="text" name="symbol"
format ="*AAA" />
</p>
<p>
<!-- Creating a single selection list. -->
Listed on:
<select name="name" title="Listed on" value="TSE">
<option value="TSE">TSE</option>
<option value="NYSE">NYSE</option>
<option value="NASDAQ">NSADAQ</option>
<option value="Dow Jones">Dow Jones</option>
</select>
</p>
<p align="right" >
<!-- Adding an image with a link. -->
<a href="www.blackberry.com">
<img src="bb_power-wee.gif" height=20 alt="BlackBerry" />
</a>
</p>
</card>

<card id="Page3" title="Stock Monitor -- Push Options">


<do type="accept" label="Next">
<go href="stock-monitor.wmls#setTriggers()"/>
</do>
<do type="accept" label="Back">
<go href="#Page2"/>
</do>
<p>
<!-- Creating a single selection list. -->
Notification trigger:
<select name="trigger" value="c">
<option value="c">Target price change</option>
<option value="r">Target high and low values</option>
</select>
</p>
<br/>
<p>
<!-- Creating a multiple selection list. -->
Include with push:
<select name="includes" multiple="true">
<option value="chart">Performance chart</option>
<option value="articles">Related articles</option>
</select>
</p>
<p align="right" >
<!-- Adding an image with a link. -->
<a href="www.blackberry.com">
<img src="bb_power-wee.gif" height=20 alt="BlackBerry" />
</a>
</p>
</card>

<card id="Page4" title="Confirm Registration Data">


<p>
You chose to monitor $(symbol), listed on $(exchange)<br/>

61
BlackBerry Wireless Handheld Browser Content Developer Guide

$(message)
</p>
<br/>
<p align="right" >
<!-- Adding an image with a link. -->
<a href="www.blackberry.com">
<img src="bb_power-wee.gif" height=20 alt="BlackBerry" />
</a>
</p>
<do type="accept" label="Submit">
<go href="stock-monitor.php" method="post">

<!-- Adding some postfields for each variable that must be


submitted. -->
<postfield name="symbol" value="$(symbol)"/>
<postfield name="exchange" value="$(exchange)"/>
<postfield name="valChange" value="$(valChange)"/>
<postfield name="valHigh" value="$(valHigh)"/>
<postfield name="valLow" value="$(valLow)"/>
<postfield name="includes" value="$(includes)"/>

<!-- Adding some postfields that define the queue for


the offline submission of the form. -->
<postfield name="x-rim-queue-id" value="Register"/>
<postfield name="x-rim-request-title" value="Stock Monitor
Registration"/>
<postfield name="x-rim-next-target" value="success.wml"/>
</go>
</do>
<do type="accept" label="Back">
<go href="#Page3"/>
</do>
</card>

<card id="Help" title="Help">

<!-- Disabling the Help soft key. -->


<do type="help" label="Help">
<noop/>
</do>
<p>
This page contains helpful hints.
</p>
<p>
For more information, click an option:
<select name="URLSelection">
<option value="rim" onpick="http://www.rim.com">
Research In Motion
</option>
<option value="blackberry" onpick="http://www.blackberry.com">
BlackBerry products
</option>
<option value="developers" onpick="http://www.blackberry.com">
BlackBerry Developer Zone
</option>
</select>
</p>
</card>

62
5: Creating a WML page

</wml>

Example: stock-monitor.wmls
function setTriggers() {

var trigger = WMLBrowser.getVar("trigger");


var change = String.find(trigger,"c");
var range = String.find(trigger,"r");
var valChange = "";
var valHigh = "":
var valLow = "";

if(change) {
var valChange = Dialogs.prompt("Change value: ","");
var message = "You will be notified when the value changes by " + valChange;
}
if(range) {
var valHigh = Dialogs.prompt("High value: "."");
var valLow = Dialogs.prompt("Low value: ", "");
var message = "You will be notified when the value reaches a high of $"
+ valHigh + " or a low of $" + valLow;
}

var ret = Browser.go("bb.wml#Page4");


}

63
BlackBerry Wireless Handheld Browser Content Developer Guide

64
6
Testing web pages
Using the simulators

Using the simulators


The BlackBerry Java Development Environment includes a BlackBerry device simulator and a Mobile Data Service
Simulator that enable you to test your web pages without using a device on an actual wireless network.

Install the simulators


Download and install the handheld and Mobile Data Service simulators from the BlackBerry Developer Zone web
site: http://www.blackberry.com/developers.

Start the simulators


1. On the Start menu, click Programs > Research In Motion > BlackBerry MDS Simulator > MDS Simulator.
2. On the Start menu, click Programs > Research In Motion > BlackBerry Device Simulator > Device Simulator.

Use the BlackBerry handheld simulator


The BalckBerry device simulator displays a Home screen with icons for each application.
1. In the BlackBerry device simulator, click the BlackBerry Browser icon.
Roll the wheel button on your mouse or click the left mouse button to select the BlackBerry Browser icon.
Click the mouse wheel button or click the right mouse button to open the application.
2. To view a web page on an internal network, open the browser menu and click Go To. Type the complete URL,
such as http://localhost/tests/sample.wml.
Tip: To open the browser menu, click the mouse wheel button or the right mouse button.
BlackBerry Wireless Handheld Browser Content Developer Guide

Trackwheel

Home screen
Escape button

Application title bar

Backspace key
Alt key Enter key
Left Shift key Right Shift key

BlackBerry device simulator for GPRS


The simulator displays icons on the Home screen for each installed application. When you select an icon, the name
of the application appears at the bottom of the screen.
When the simulator window is active, you can roll the wheel button on your mouse to simulate rolling the
trackwheel, and click the wheel button to simulate clicking the trackwheel. If your mouse does not have a wheel
button, click and drag the left mouse button to simulate rolling the trackwheel, and click the right mouse button
to simulate clicking the trackwheel.
To open an application, roll the trackwheel to select the appropriate icon and click the trackwheel. The
application’s main screen appears.
Press the keys on your computer keyboard or click the keys on the simulator keyboard to simulate pressing
handheld keys.
See the BlackBerry device simulator online help for more information.

66
7
Creating browser push applications
Push applications
The Mobile Data Service push process
Mobile Data Service push applications
Writing Mobile Data Service push applications
Troubleshooting push applications

Push applications
Note: Push applications require BlackBerry Enterprise Server for Microsoft Exchange version 3.5 or later, or BlackBerry
Enterprise Server for IBM Lotus Domino version 2.2 or later, with the Mobile Data Service enabled.

Push applications enable you to send new web content and alerts to specific users. Users do not have to request or
download the data because the push application delivers the information as it becomes available.
There are two types of push applications:
• Browser push applications: Web content is sent to the browser on the handheld. The BlackBerry Browser
configuration supports Mobile Data Service push applications. WAP Browser configuration supports WAP
push applications. Push applications are not supported by the Internet Browser configuration.
• Client/server push applications: Data is sent to a custom Java application on the handheld. Client/server
push applications consist of a custom client application for the handheld and a server-side application that
pushes content to it. This approach provides more control over the type of content that you can send out and
how this data is processed and displayed on the handheld compared to browser push applications. See the
BlackBerry Applications Developer Guide Volume 1 -- Fundamentals, for information on writing custom Java
applications.

BlackBerry Browser push support


The BlackBerry Enterprise Server, with the Mobile Data Service enabled, manages the flow of data from the push
application to the handheld using the same encrypted channel that is used for data communication between the
handheld and the BlackBerry Enterprise Server. The push application sends data to users based on their email
addresses. With a central database of the handheld users in the organization, the BlackBerry Enterprise Server
directs content to the appropriate handhelds. The BlackBerry Infrastructure manages the connection to the
wireless network and verifies that content is delivered to users as soon as they are in a sufficient wireless coverage
area.
Prerequisites: The handheld must be provisioned with the MDS (IPPP) Transport and MDS (IPPP) Browser Configuration
service book entries. See "Service book records" on page 28 for more information.
System administrators must enable the Mobile Data Service central push server. See the BlackBerry Enterprise Server
Administration Guide for information.
BlackBerry Wireless Handheld Browser Content Developer Guide

Server applications push content to handhelds by sending HTTP POST requests to the BlackBerry Enterprise Server.
The Mobile Data Service feature of the BlackBerry Enterprise Server forwards the content to the appropriate
handhelds, based on user email addresses. On the handheld, a separate browser push listener thread listens on
port 7874 for incoming messages and processes those messages.
The Mobile Data Service supports two push service implementations:
• RIM Push: Sends the push content as a byte stream to the destination user and port that is specified in the
URL of the push message. All push data is stored in RAM of the Mobile Data Service server.
• Push Application Protocol (PAP): Sends an HTTP POST request containing a PAP message. This message is a
MIME multipart message that includes an XML document specifying the control entity and the push content.
The control entity contains information about the destination handheld address, message ID, delivery time
stamps, and so on.

Push methods
Web content is pushed to the browser in one of the following ways:
• Message: Applications can push content pages to the handheld. Content pages appear as browser messages
in the handheld messages list. The message push request might include a descriptive title, which appears in
the messages list. Otherwise, the browser message displays the URL. Users open the browser message to view
the specified page in the browser.
Push applications can include the content in the browser message, so that the browser renders the pushed
content immediately in the handheld messages list. Alternatively, the application can include only the URL, so
that the browser performs a normal fetch operation to retrieve the content when the user requests it, either
from the local cache or from the network.
• Channel: Applications can push data to the handheld that create or update channels, which appear on the
handheld Home screen with a custom icon. Channels act as browser-based applications on the handheld for
regular updates of certain types of data.
A channel push request can include URLs for two icons:
• one to indicate that content is new or updated
• one to indicate that content has been read
These icons must be 28-by-28 pixel .png images. Depending on the handheld capabilities, content developers
can design monochrome or 16-color icons. The channel push message can specify the position on the Home
screen that the channel should occupy.
When the handheld receives a channel push message, it creates a new channel, or updates the channel if it
already exists. When a channel has been added or updated, an icon appears on the Home screen to alert users
that content is available. For example, an order-tracking channel could change the icon as product orders are
entered. Users click the icon to open an instance of the browser that displays the pushed content.

68
7: Push applications

Channel push requests include a channel identifier that uniquely describes the channel. Push applications can
delete a channel and remove the icon from the handheld Home screen by sending another push request with
the ID of the channel to delete.
Users can remove pushed channels from the Home screen.
Note: Deleting a channel removes only the instance of the channel that is currently stored on the handheld. If the
server pushes the channel again, it reappears on the Home screen.

• Cache — Applications can push content directly to the browser cache. Pushing content to the cache enables
users to access the content quickly, even when they are outside a wireless coverage area. Cache push content
can be associated with a channel. If a channel identifier is specified, the content URL is added to the
appropriate channel (if the channel is already active on the handheld) and to the persistent cache. Otherwise,
the content is added to the persistent cache only. There is no indication to the user that the content has been
updated. The next time that the user visits the specified URL, the browser retrieves the content from the
cache.
When an application pushes data to the browser cache, the application can include an expiry time that
defines how long the data remains in the cache before it is removed.

Reliable pushes
Push application developers can configure their push applications to provide acknowledgement upon the
successful delivery of a push submission. This enables them to verify that content has reached the handheld.
the following two levels of acknowledgement are available:
• Transport Level: In this case, a message is sent from the handheld acknowledging that the content has arrived
at the destination handheld. Transport level acknowledgment provides a guarantee that the data has been
delivered to the handheld; there is, however, no guarantee that the data has been delivered to the client
application.
Transport level acknowledgement is supported for all destination handhelds. If no acknowledgement level is
specified by the push application, transport level is assumed.
• Application Level: In this case, a message is sent after the content has reached the intended client
application.
Application level acknowledgement is only supported by those handhelds running version 4.0 of the
BlackBerry handheld software.
To maximize the reliability of push messages, push application developers can specify an Application Level
Acknowledgement Preferred setting, which uses application-level acknowledgements for those handhelds running
version 4.0 of the handheld software and transport-level acknowledgements for those handhelds that are not.

Additional push application features


Both RIM Push and PAP Push service implementations support the following tasks:
• Push submission result notification: Enables push application developers to notify users that a push has
arrived on their handheld.

69
BlackBerry Wireless Handheld Browser Content Developer Guide

• Deliver-Before time-stamp: Enables push application developers to provide a time stamp before which the
push is required to be delivered. If a push is not successfully delivered by the specified time, the push is
considered to have failed.
The following additional tasks are supported by the PAP push service implementation only:
• Deliver-After time-stamp: Enables push application developers to provide a time stamp before which the push
must not be delivered. If a push is not successfully delivered after the specified time, the push is considered to
have failed.
• Push cancellation: Enables push applications to cancel a push submission that has already been sent.
• Push status query: Enables push applications to check the status of a push submission.

WAP Browser push support


For the WAP Browser, a WAP Push service record must be provisioned on the handheld to push data to the
handheld. WAP Push service records are usually sent to the handheld during registration.

Push methods
Server applications push content to the handheld using one of three methods.
• Existing WAP connections: This option is only available when a WAP connection is open between the
handheld and the WAP gateway.
• SMS messages: If an existing WAP connection is not available, the service record provisioned for the GPRS and
CDMA networks typically uses SMS.
In addition, service providers can restrict incoming SMS messages to specific sources. The source address
restrictions are specified as parameters in the WAP Push service record that is sent during registration.
• UDP messages: If an existing WAP connection is not available, the service record provisioned for the iDEN
network typically uses UDP.
On the handheld, the WAP Push service record contains information on how the handheld can receive WAP
pushes. The service record also specifies on which ports the WAP Push Processor listens for incoming WAP Push
messages and how those incoming messages are handled.

Push message types


WAP Push accepts two different message types.
• Service indications: These are self-contained messages with some text to inform the user about some event or
notification. The entire text of the message is included in the service indication that is pushed to the
handheld.
• Service loadings: These messages contain a URL that points to the real content. The service loading message
is pushed to the handheld first, and then the browser automatically downloads content from the URL
location.
When a push message is successfully or unsuccessfully processed by the content-specific push handler, a push
completion notification is sent back to the push gateway.

70
7: The Mobile Data Service push process

By default both service indication and service loading messages are handled by the browser automatically. Users
can change how incoming push messages are handled or disable the browser push feature in the browser
configuration properties.

The Mobile Data Service push process


Your push application sends an HTTP POST request to the Mobile Data Service, which specifies the handhelds and
ports to send the content to. The Mobile Data Service receives the HTTP request, initiates the HTTP connections to
the handhelds, and sends the data. The browser listens on port 7874 to receive the data.
1. The push application sends an HTTP POST request to the Mobile Data Service on the web server listen port.
The default port is 8080 for the Mobile Data Service Simulator and IBM Lotus Domino, and 8300 for
Microsoft Exchange.
2. The Mobile Data Service sends an acknowledgement to the push application.
3. The Mobile Data Service closes the connection.
4. The Mobile Data Service converts the content of the request, if necessary, and sends it to the BlackBerry
Enterprise Server, which compresses and encrypts the content before sending it to handhelds.
5. Handhelds receive the pushed content.
6. Handhelds return an acknowledgement to Mobile Data Service.
Note: System administrators set a Flow control timeout parameter for Mobile Data Service that defines the length of
time that Mobile Data Service waits for the handheld to return an acknowledgement before it discards pending data.
The push application does not receive an error message if the pushed data does not reach the handheld.

Central push server


In many organizations, BlackBerry user accounts are distributed among several BlackBerry Enterprise Servers. To
simplify application development, one Mobile Data Service can be enabled as the central push server. See the
BlackBerry Enterprise Server Handheld Management Guide for more information.
When you write a push application, you do not need to know the BlackBerry Enterprise Server on which each user
resides. The push application sends the HTTP POST request to the Mobile Data Service that is enabled as the
central push server. This Mobile Data Service forwards the request to the Mobile Data Service on the BlackBerry
Enterprise Servers on which the recipients reside.
The Mobile Data Service listens for push connections on the port defined by the push server connection listen
port. (The default listen port is 81.)

Mobile Data Service push applications


1. The application server sends an HTTP POST request to the Mobile Data Service using the following format:

71
BlackBerry Wireless Handheld Browser Content Developer Guide

post/push?DESTINATION=<destination>&PORT=7874&REQUESTURI=<request_URI>
<header><content>
Note: The browser listens on port 7874.

2. The Mobile Data Service receives the HTTP request. It stores the destination and port information, and then
formats the request as follows:
post <request_URI><header><content>

3. If applicable, the Mobile Data Service applies a transcoder according to its transcoder rules.
The push request can override these rules to request a specific transcoder by using the transfer-encoding
header. For example, if the HTTP header transfer-encoding: vnd.wap.wml is set, the Mobile Data Service
runs the wml transcoder before it pushes the data to the handheld.
4. The Mobile Data Service sends the content to the handheld.

Mobile Data Service push application HTTP headers


Each pushed message can include the content and several attributes. Attributes are encoded as HTTP headers.

HTTP Header Description


X-Rim-Push-Type Specifies how the content is pushed to the browser.
Values Description
Browser-Message Pushes content as a browser message to the messages list.
Browser-Content Pushes content directly to the browser’s content cache. The next time
that the user visits the specified URL, the browser retrieves the
updated content from the cache.
Browser-Channel Pushes content to the Home Screen, where it is added as an icon.
When clicked, the icon opens the browser, which displays the pushed
content. You must specify a channel ID. If the channel ID already
exists, that channel is updated with the new content.
Browser-Channel-Delete Removes the channel with the given channel ID from the Home
Screen.
X-Rim-Push-Channel-ID Identifies the channel that is added, updated or removed.
Values Description
<unique_ID> A string that uniquely identifies a new or existing channel.
X-Rim-Push-Title Identifies the name used to identify the push icon on the Home Screen.
Values Description
<title> A string that identifies the push icon.
X-Rim-Push-Read-Icon-URL Identifies the icon that is displayed on the Home Screen after a channel push has been viewed by the
user.
Values Description
<icon_URL> The URL of the image that is used as the read icon.

72
7: Mobile Data Service push applications

HTTP Header Description


X-Rim-Push-Unread-Icon-URL Identifies the icon that is displayed on the Home Screen to indicate that a channel push has not yet
been viewed by the user.
Values Description
<icon_URL> The URL of the image to be used as the unread icon for the push
application.
X-Rim-Push-Ribbon-Position Defines the location of the channel push icon on the handheld Home Screen.
Values Description
<position_number> An integer representing the position of the icon on the Home Screen.
X-Rim-Push-Description Provides a brief description of the push application.
Values Description
<description_string> A string that describes the push application.
X-Rim_Push-Priority Specifies what kind of notification users receive when content is pushed to the handheld.
Values Description
High The user is notified using the user-specified Browser Message Profile
notification (for example, a ring tone or vibration). In addition, an
unread icon is added to the Home Screen, and a dialog box is
displayed, which states that a new push has been received.
Medium The user is notified using the user-specified Browser Message Profile
notification (for example, a ring tone or vibration) and an unread
icon is added to the Home Screen.
Low The user is notified using the user-specified Browser Message Profile
notification (for example, a ring tone or vibration) and an unread
icon is added to the Home Screen.
None An unread icon is added to the Home Screen.
X-Rim_Push-Reliability Specifies the delivery reliability mode of the content.
Values Description
Transport Default. Sends a message from the handheld acknowledging that the
content has arrived.
Transport level acknowledgement is supported for all destination
handhelds.
Application Sends an acknowledgement message from the handheld only when
the content has reached the intended client application.
Application level acknowledgement is only supported by handhelds
that are running version 4.0 of the BlackBerry handheld software.
Application-Preferred Sends application-level acknowledgement from handhelds that are
running at least version 4.0 of the software and transport-level
acknowledgement from handhelds running earlier versions.
X-Rim-Push-NotifyURL Specifies a URL to which a result notification is sent.
Values Description
<notification_URL> The URL to which the result notification is sent.

73
BlackBerry Wireless Handheld Browser Content Developer Guide

HTTP Header Description


X-Rim-Push-Deliver-Before Specifies the date and time by which the content must be delivered to the handheld. Content
that has not been delivered before this date is not delivered.
Values Description
<delivery_date> The time, specified in HTTP format, before which the content must be
delivered.
X-Rim-Push-ID This header specifies a unique message ID, which can be used to cancel or check the status of a
message.
Values Description
<unique_ID> A string which uniquely identifies the message.
Typically, you should specify a URL with a value, such as
[email protected].
X-Rim-Transcode-Content Specifies which types of pushed content the server should transcode.
Values Description
*/* The server transcodes all content.
none The server does not transcode any content.
<list-of-MIME-types> The server transcodes content types in the given comma-separated
list of MIME types. For example:
X-Rim-Transcode-Content: image/png,
image/jpeg, image/vnd.wap.wbmp
Content-Location Defines the URL from which the content is downloaded.
Values Description
<content_URL> A string specifying the URL at which the content can be found.
Content-Type Defines which MIME types can be included in the pushed content.
Values Description
<list-of-MIME-types> A comma-separated list of MIME types. For example:
X-Rim-Transcode-Content: image/png,
image/jpeg, image/vnd.wap.wbmp
Cache-Control Specifies the caching parameters for the pushed content.
Values Description
no-cache The content is not cached.
max-age The time, in seconds, before cached content expires.
must-revalidate The page is always re-fetched, even when going back in the History
list.

Writing Mobile Data Service push applications


The following procedure demonstrates how to write code for a reliable Mobile Data Service channel push
application that performs the following requests:
• HTTP GET request, which retrieves content from the content server
• HTTP POST request, which sends content to Mobile Data Service

74
7: Writing Mobile Data Service push applications

The procedures that follow outline the general steps that are required to create push applications that create icons
on the handheld Home screen. When users click this icon, a web page appears. An example exists for each of the
Mobile Data Service push service implementations.
• See “Writing a RIM push application” on page 75 for an example of a RIM push application.
• See “Writing a PAP push application” on page 82 for an example of a PAP push application.
Complete sample code for each example is provided at the end of each section.
Note: You should push data based on users’ email addresses so that users continue to receive updates even if they
change handhelds or networks. Mobile Data Service provides the mapping between email addresses and handheld
PINs.

Writing a RIM push application


This section demonstrates how to write a push application that uses the RIM push service implementation to
create an icon on the handheld Home Screen.
See “BrowserChannelPush.java (RIM push service implementation)” on page 78 for the complete code sample.
See “rim_browserpush.properties file” on page 81 for a sample property file.

Write a push method


1. Define a method that accepts the parameters that are for a channel push.
public static void pushPage(String mdsHostName, int mdsPort, String email,
String pushUrlString, String pushType, String pushTitle,
String unreadIconUrl, String readIconUrl,
String pushReliability, String notifyUrl,
String PushId) {
2. Define variables for connections to two URLs: one to the server with the content and one to Mobile Data
Service.
HttpURLConnection pushConn;
HttpURLConnection mdsConn;
URL pushUrl;
URL mdsUrl;
3. Create the connection to Mobile Data Service by invoking the openConnection method on the URL. The
push listener thread on the handheld listens on port 7874.
mdsUrl = new URL("http", mdsHostName, mdsPort, "push?DESTINATION=" + email +
"&PORT=7874&REQUESTURI=/");
mdsConn = (HttpURLConnection)mdsUrl.openConnection();
4. Set additional header properties for the push.
mdsConn.setRequestProperty("Content-Location", pushUrlString);
mdsConn.setRequestProperty("X-Rim-Push-Title", pushTitle);
mdsConn.setRequestProperty("X-Rim-Push-Type", pushType);
if (pushType.equals(CHANNEL) || pushType.equals(CHANNEL_DELETE)) {
mdsConn.setRequestProperty("X-Rim-Push-Channel-ID", pushUrlString);
if (pushType.equals(CHANNEL)) {
mdsConn.setRequestProperty("X-Rim-Push-UnRead-Icon-URL",
unreadIconUrl);

75
BlackBerry Wireless Handheld Browser Content Developer Guide

mdsConn.setRequestProperty("X-Rim-Push-Read-Icon-URL",
readIconUrl);
}
}
mdsConn.setRequestProperty("X-Rim-Push-Reliability", pushReliability);
mdsConn.setRequestProperty("X-Rim-Push-NotifyURL", notifyUrl);
mdsConn.setRequestProperty("X-Rim-Push-ID", pushId);
try {
mdsConn.setRequestMethod("POST");
} catch (ProtocolException e) {
throw new RuntimeException("problems setting request method: " +
e.getMessage());
}
mdsConn.setAllowUserInteraction(false);
mdsConn.setDoInput(true);
mdsConn.setDoOutput(true);

5. Invoke the openConnection method on the URL to connect to the content server.
pushUrl = new URL(pushUrlString);
pushConn = (HttpURLConnection)pushUrl.openConnection();
6. Set properties for the HTTP GET request to the content server.
pushConn.setAllowUserInteraction(false);
pushConn.setDoInput(true);
pushConn.setDoOutput(false);
pushConn.setRequestMethod("GET");
7. Open the connection to the content server.
pushConn.connect();
8. Set properties for the HTTP POST request to Mobile Data Service. Copy the header properties from the GET
request and then set additional properties for the push.
String name;
String value;
for (int i = 0; true; i++) {
name = pushConn.getHeaderFieldKey(i);
value = pushConn.getHeaderField(i);
if ((name ==null) && (value == null)) { break; }
if ((name ==null) || (value == null)) { continue; }
if (name.equals("X-Rim-Push-Type")) { continue; }
if (name.equals("Transfer-Encoding")) { continue; }
System.out.println("setting header property " + name + "= " + value);
mdsConn.setRequestProperty(name, value);
}

9. Read content from the content server connection and write it to Mobile Data Service connection.
InputStream ins = pushConn.getInputStream();
OutputStream outs = mdsConn.getOutputStream();
copyStreams(ins, outs);
Tip: This step is optional for applications that use the channel or message push methods. If you do not push content to
the handheld, the browser fetches the content when the user requests it.
If you are pushing content to many users, copy the content to a temporary file to avoid multiple requests to the content
server.

76
7: Writing Mobile Data Service push applications

10. Open the connection to Mobile Data Service.


mdsConn.connect();
...
11. Retrieve the response code that is returned from Mobile Data Service and display a status message.
int rescode = mdsConn.getResponseCode();
if (rescode != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Cannot push data, received bad response code
from Mobile Data Service: " + rescode);
}
System.out.println("Pushed page to the handheld");

Create a method that reads a property file and pushes the page
1. Define the method that accepts an array of arguments.
public static void main(String[] args) {
2. Read values from the property file.
Properties prop = new Properties();
try {
prop.load(new FileInputStream(PROPERTIES_FILE));
}catch (FileNotFoundException fnfe) {
throw new RuntimeException("property file not found: " + fnfe.getMessage());
} catch (IOException ioe) {
throw new RuntimeException("problems reading property file: " +
ioe.getMessage());
}

String mdsHostName = prop.getProperty("mdsHostName");


int mdsPort = (new Integer(prop.getProperty("mdsPort"))).intValue();

String email = prop.getProperty("email");

String pushUrlString = prop.getProperty("pushUrlString");


String pushType = prop.getProperty("pushType").trim();
String pushTitle = prop.getProperty("pushTitle");

String unreadIconUrl = prop.getProperty("unreadIconUrl");


String readIconUrl = prop.getProperty("readIconUrl");

String pushReliability = prop.getProperty("pushReliability");


String notifyUrl = prop.getProperty("notifyUrl");
String pushID = prop.getProperty("pushId");

3. Invoke the pushPage method that you created in “Write a push method” on page 75.
pushPage(mdsHostName, mdsPort, email, pushUrlString, pushType, pushTitle,
unreadIconUrl, readIconUrl, pushReliability, notifyUrl, PushId);

Set up and test the example


1. Deploy the web content and push icons that you want to push to handhelds on a web application server.
2. Place the BrowserChannelPush.java and rim_browserpush.properties files into a
com\rim\docs\samples\browserchannelpush folder that is in your CLASSPATH.

77
BlackBerry Wireless Handheld Browser Content Developer Guide

3. Edit the rim_browserpush.properties file to specify the location and names of the files to push to the
handheld.
4. Start the Mobile Data Service and handheld simulators.
5. Enable Mobile Data Service push functionality in the handheld simulator.
6. Compile and run the java file.
In the handheld simulator, the icon that is specified in the unreadIconUrl property appears on the handheld
Home screen. Click the icon to view the web page that is specified in the pushUrlString property.

Delete the channel


If necessary, delete the channel.
1. Edit the rim_browserpush.properties file.
2. Change the pushType parameter to pushType = Browser-Channel-Delete.
3. Compile and run BrowserChannelPush.java again. The channel icon is removed from the Home screen in the
handheld simulator.

Example: BrowserChannelPush.java (RIM push service implementation)

/*
* BrowserChannelPush.java
* Copyright (C) 2004 Research In Motion Limited. All rights reserved.
*/

package com.rim.docs.samples.browserchannelpush;

import java.net.*;
import java.io.*;
import java.util.*;

public class BrowserChannelPush {

public static final String CHANNEL = "Browser-Channel";


public static final String CHANNEL_DELETE = "Browser-Channel-Delete";
private static final String PROPERTIES_FILE = "com/rim/docs/samples/browserchannelpush/
rim_browserpush.properties";

public BrowserChannelPush() { }

/* Main method to read in property file and invoke the push method. */

public static void main(String[] args) {


// load the properties file
Properties prop = new Properties();
try {
prop.load(new FileInputStream(PROPERTIES_FILE));
}catch (FileNotFoundException fnfe) {
throw new RuntimeException("property file not found: " + fnfe.getMessage());
} catch (IOException ioe) {
throw new RuntimeException("problems reading property file: " + ioe.getMessage());
}

78
7: Writing Mobile Data Service push applications

// The host name and port of Mobile Data Service to perform the push.
String mdsHostName = prop.getProperty("mdsHostName");
int mdsPort = (new Integer(prop.getProperty("mdsPort"))).intValue();

// Handheld PIN to which to push the page.


String email = prop.getProperty("email");

// URL of the page to push.


String pushUrlString = prop.getProperty("pushUrlString");
String pushType = prop.getProperty("pushType").trim();
String pushTitle = prop.getProperty("pushTitle");

// URLs of the icons to use for Browser-Channel push type.


String unreadIconUrl = prop.getProperty("unreadIconUrl");
String readIconUrl = prop.getProperty("readIconUrl");

// URLs of the icons to use for Browser-Channel push type.


String pushReliability = prop.getProperty("pushReliability");
String notifyUrl = prop.getProperty("notifyUrl");
String pushID = prop.getProperty("pushId");

// Push the page to the handheld.


pushPage(mdsHostName, mdsPort, email, pushUrlString, pushType, pushTitle,
unreadIconUrl, readIconUrl, pushReliability, notifyUrl, PushId);
}

/* Method to push a web page to a handheld. */


public static void pushPage(String mdsHostName, int mdsPort, String email, String
pushUrlString, String pushType, String pushTitle, String unreadIconUrl,
String readIconUrl, String pushReliability, String notifyUrl, String
PushId) {

System.out.println("mdsHostName = " + mdsHostName);


System.out.println("mdsPort = " + mdsPort);
System.out.println("email = " + email);
System.out.println("pushUrlString = " + pushUrlString);
System.out.println("pushType = " + pushType);
System.out.println("pushTitle = " + pushTitle);
System.out.println("unreadIconUrl = " + unreadIconUrl);
System.out.println("readIconUrl = " + readIconUrl);
System.out.println("Reliability = " + pushReliability);
System.out.println("Notification URL= " + notifyUrl);
System.out.println("Message ID= " + PushId);

/* Two HttpURLConnections are used. One connects to the URL of the page to
* push and reads the page from there. The other connects to the BlackBerry
* Enterprise Server and writes the page to the server for pushing to the
* handheld.
*/

HttpURLConnection pushConn;
HttpURLConnection mdsConn;
URL pushUrl;
URL mdsUrl;
try {
mdsUrl = new URL("http", mdsHostName, mdsPort, "push?DESTINATION=" + email +
"&PORT=7874&REQUESTURI=/");

79
BlackBerry Wireless Handheld Browser Content Developer Guide

mdsConn = (HttpURLConnection)mdsUrl.openConnection();

/* Set additional header properties for the push. */

mdsConn.setRequestProperty("Content-Location", pushUrlString);
mdsConn.setRequestProperty("X-RIM-Push-Title", pushTitle);
mdsConn.setRequestProperty("X-RIM-Push-Type", pushType);
if (pushType.equals(CHANNEL) || pushType.equals(CHANNEL_DELETE)) {
mdsConn.setRequestProperty("X-RIM-Push-Channel-ID", pushUrlString);
if (pushType.equals(CHANNEL)) {
mdsConn.setRequestProperty("X-RIM-Push-UnRead-Icon-URL", unreadIconUrl);
mdsConn.setRequestProperty("X-RIM-Push-Read-Icon-URL", readIconUrl);
}
}
mdsConn.setRequestProperty("X-RIM-Push-Reliability", pushReliability);
mdsConn.setRequestProperty("X-RIM-Push-NotifyURL", notifyUrl);
mdsConn.setRequestProperty("X-RIM-Push-ID", pushId);

try {
mdsConn.setRequestMethod("POST");
} catch (ProtocolException e) {
throw new RuntimeException("problems setting request method: " +
e.getMessage());
}

mdsConn.setAllowUserInteraction(false);
mdsConn.setDoInput(true);
mdsConn.setDoOutput(true);

if (!pushType.equals(CHANNEL_DELETE)) {
//no need to connect to the pushed page for deletion
try {
pushUrl = new URL(pushUrlString);
} catch (MalformedURLException e) {
throw new RuntimeException("invalid push URL: " + e.getMessage());
}
pushConn = (HttpURLConnection)pushUrl.openConnection();
pushConn.setAllowUserInteraction(false);
pushConn.setDoInput(true);
pushConn.setDoOutput(false);
pushConn.setRequestMethod("GET");
pushConn.connect();

/* Read the header properties from the push connection and


* write them to Mobile Data Service connection.
*/

String name;
String value;

for (int i = 0; true; i++) {


name = pushConn.getHeaderFieldKey(i);
value = pushConn.getHeaderField(i);
if ((name ==null) && (value == null)) { break; }
if ((name ==null) || (value == null)) { continue; }
if (name.equals("X-RIM-Push-Type")) { continue; }
if (name.equals("Transfer-Encoding")) { continue; }
System.out.println("setting header property " + name + "= " + value);

80
7: Writing Mobile Data Service push applications

mdsConn.setRequestProperty(name, value);
}

/*
* Read content from the push connection and write it to the
* MDS connection.
*/

InputStream ins = pushConn.getInputStream();


OutputStream outs = mdsConn.getOutputStream();
copyStreams(ins, outs);
}
System.out.println("Connecting to " + mdsHostName + ":" + mdsPort);
mdsConn.connect();
int rescode = mdsConn.getResponseCode();
if (rescode != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Cannot push data, received bad response code from
Mobile Data Service: " + rescode);
}
System.out.println("Pushed page to the handheld");
} catch (IOException e) {
throw new RuntimeException("Cannot push page:" + e.toString());
}
}

/* Method to read data from the input stream and copy it to the output stream. */
private static void copyStreams(InputStream ins, OutputStream outs)
throws IOException {
int maxRead = 1024;
byte [] buffer = new byte[1024];
int bytesRead;

for(;;) {
bytesRead = ins.read(buffer);
if (bytesRead <= 0) {break;}
outs.write(buffer, 0, bytesRead);
}
}
}

Example: rim_browserpush.properties file

# rim_browserpush.properties file

# Push from Mobile Data Service simulator on the local computer to handheld simulator.
mdsHostName = localhost

# mdsPort must match WebServer.listen.port set in Mobile Data Service rimpublic.property


file.
mdsPort = 8080

# Simulator email (mapping to simulator PIN is set in MDS rimpublic.property file).


email = user2100000a@@pushme.com

#pushType = Browser-Content

81
BlackBerry Wireless Handheld Browser Content Developer Guide

#pushType = Browser-Message
pushType = Browser-Channel
#pushType = Browser-Channel-Delete
pushTitle = Have a Great Day!

# The actual page (and icons) to push.


pushUrlString = http://localhost/testpage/sample.htm
unreadIconUrl = http://localhost/testpage/smile_unread.png
readIconUrl = http://localhost/testpage/smile.png

# The reliability settings.


pushReliability = application-preferred
notifyUrl = http://localhost/ReceivePushNotification
PushId = [email protected]

Writing a PAP push application


This section demonstrates how to write a push application that uses the PAP push service implementation to
create an icon on the handheld Home Screen.
See “BrowserPushDemo.java (PAP push service implementation)” on page 87 for the complete code sample.
See “pap_browserpush.properties file” on page 92 for a sample property file.

Write a push method


1. Define a method that accepts the required parameters for a channel push.
public static void pushPage(String mdsHostName, int mdsPort, String email,
String pushUrlString, String pushType, String pushTitle,
String unreadIconUrl, String readIconUrl,
String pushReliability, String notifyUrl,
String PushId) {
2. Define variables for connections to the Mobile Data Service.
HttpURLConnection mdsConn;
URL mdsUrl;
3. Create the connection to Mobile Data Service by invoking the openConnection method on the URL. The
push listener thread on the handheld listens on port 7874.
mdsUrl = new URL("http", mdsHostName, mdsPort, "/pap");
mdsConn = (HttpURLConnection)mdsUrl.openConnection();
4. Set additional header properties for the push.
try {
String protocol = "http";
if (useHttps == true) {
protocol += "s";
}
mdsUrl = new URL(protocol, mdsHostName, mdsPort, "/pap");
mdsConn = (HttpURLConnection)mdsUrl.openConnection();
if ((user != null) && (password != null)) {
String authString = user + ":" + password;
mdsConn.setRequestProperty("Authorization", "Basic " + new
BASE64Encoder().encode(authString.getBytes()));

82
7: Writing Mobile Data Service push applications

}
String boundary = "";
if ((command == 'p') || (command == 'r')) {
boundary = "asdlfkjiurwghasf";
mdsConn.setRequestProperty("Content-Type", "multipart/related;
type=\"application/xml\"; boundary=" + boundary);
mdsConn.setRequestProperty("X-Wap-Application-Id", "/");
mdsConn.setRequestProperty("X-Rim-Push-Dest-Port", "7874");
}
else {
mdsConn.setRequestProperty("Content-Type", "application/xml");
}

mdsConn.setRequestProperty("Content-Location", pushUrlString);
mdsConn.setRequestProperty("X-RIM-Push-Title", pushTitle);
mdsConn.setRequestProperty("X-RIM-Push-Type", pushType);
if (pushType.equals(CHANNEL) || pushType.equals(CHANNEL_DELETE)) {
mdsConn.setRequestProperty("X-RIM-Push-Channel-ID", pushUrlString);
if (pushType.equals(CHANNEL)) {
mdsConn.setRequestProperty("X-RIM-Push-UnRead-Icon-URL", unreadIconUrl);
mdsConn.setRequestProperty("X-RIM-Push-Read-Icon-URL", readIconUrl);
}
}

try {
mdsConn.setRequestMethod("POST");
} catch (ProtocolException e) {
throw new RuntimeException("problems setting request method: " +
e.getMessage());
}

mdsConn.setAllowUserInteraction(false);
mdsConn.setDoInput(true);

5. Open the connection to Mobile Data Service.


mdsConn.connect();
...
6. Retrieve the response code that is returned from Mobile Data Service and display a status message.
int rescode = mdsConn.getResponseCode();
if (rescode != HttpURLConnection.HTTP_OK) {
throw new RuntimeException("Cannot push data, received bad response code
from Mobile Data Service: " + rescode);
}
System.out.println("Pushed page to the handheld");

Create a method to retrieve the content


1. Define a method that accepts the parameters that are required to define the push content.
private static String[] getContent(String pushUrlString, String pushType, String
pushTitle, String unreadIconUrl, String readIconUrl) {

2. Define variables for connections to two URLs: one to the server with the content and one to Mobile Data
Service.
HttpURLConnection pushConn = null;
URL pushUrl;

83
BlackBerry Wireless Handheld Browser Content Developer Guide

3. Invoke the openConnection method on the URL to connect to the content server.
StringBuffer contentHeaders = new StringBuffer();
try {
pushUrl = new URL(pushUrlString);
} catch (MalformedURLException e) {
throw new RuntimeException("invalid push URL: " + e.getMessage());
}
pushConn = (HttpURLConnection)pushUrl.openConnection();
4. Set properties for the HTTP GET request to the content server.
pushConn.setAllowUserInteraction(false);
pushConn.setDoInput(true);
pushConn.setDoOutput(false);
pushConn.setRequestMethod("GET");
5. Open the connection to the content server.
pushConn.connect();

6. Set properties for the HTTP POST request to Mobile Data Service. Copy the header properties from the GET
request and then set additional properties for the push.
String name, value;
for (int i = 0; true; i++) {
name = pushConn.getHeaderFieldKey(i);
value = pushConn.getHeaderField(i);
if ((name ==null) && (value == null)) { break; }
if ((name ==null) || (value == null)) { continue; }
if (name.equals("X-RIM-Push-Type")) { continue; }
if (name.equals("Transfer-Encoding")) { continue; }
contentHeaders.append("\r\n").append(name).append(": ").append(value);
}
content[0] = contentHeaders.toString();

7. Read content from the content server connection and write it to Mobile Data Service connection.
InputStream ins = pushConn.getInputStream();
ByteArrayOutputStream bouts = new ByteArrayOutputStream();
copyStreams(ins, bouts);
ins.close();
content[1] = new String(bouts.toByteArray());

return content;
Tip: This step is optional for applications that use the channel or message push methods. If you do not push content to
the handheld, the browser fetches the content when the user requests it.
If you are pushing content to many users, copy the content to a temporary file to avoid multiple requests to the content
server.

Create a method that reads a property file and pushes the page
1. Define the method that accepts an array of arguments that includes the PAP command and PushID.
public static void main(String[] args) {

84
7: Writing Mobile Data Service push applications

2. Configure the method to send a different XML file based on the PAP command issued.
char command = args[0].charAt(0);
String papFilename;
switch (command)
{
case 'p':
papFilename = "pap_push.txt";
break;
case 's':
papFilename = "pap_status.txt";
break;
case 'c':
papFilename = "pap_cancel.txt";
break;
case 'r':
papFilename = "pap_replace.txt";
break;
default:
System.out.println("invalid command");
return;
}
3. Read values from a property file.
Properties prop = new Properties();
try {
prop.load(new FileInputStream(PROPERTIES_FILE));
} catch (FileNotFoundException fnfe) {
throw new RuntimeException("property file not found: " + fnfe.getMessage());
} catch (IOException ioe) {
throw new RuntimeException("problems reading property file: " +
ioe.getMessage());
}

String mdsHostName = prop.getProperty("mdsHostName").trim();


int mdsPort = (new Integer(prop.getProperty("mdsPort").trim())).intValue();
String pushUrlString = prop.getProperty("pushUrlString").trim();
String pushType = prop.getProperty("pushType", CHANNEL).trim();
String pushTitle = prop.getProperty("pushTitle", "Push Page").trim();
String unreadIconUrl = prop.getProperty("unreadIconUrl", "").trim();
String readIconUrl = prop.getProperty("readIconUrl", "").trim();
String user = prop.getProperty("user");
String password = prop.getProperty("password");

boolean useHttps = false;


try {
useHttps = Boolean.valueOf(prop.getProperty("useHttps")).booleanValue();
} catch (Exception e) { }

if (useHttps == true) {
System.setProperty("javax.net.ssl.trustStore",
"C:\\p4\\main\\IPProxyProject\\webserver\\webserver.keystore");
System.setProperty("javax.net.ssl.trustStorePassword", "password");
}

String pushId = args[1];

String replaceId = "";

85
BlackBerry Wireless Handheld Browser Content Developer Guide

if (command == 'r') {
System.out.print("Enter push id to replace: ");
replaceId = (new BufferedReader(new
InputStreamReader(System.in))).readLine().trim();
}

4. Invoke the getContent method that you created in “Create a method to retrieve the content” on page 83 to
retrieve the content.
String[] content = null;
if ((command == 'p') || (command == 'r')) {
content = getContent(pushUrlString, pushType, pushTitle, unreadIconUrl,
readIconUrl);
}

5. Invoke the pushPage method that you created in “Write a push method” on page 82.
pushPage(command, pushId, replaceId, papFilename, mdsHostName, mdsPort, pushType,
user, password, useHttps, content);

Set up and test the example


1. Create the XML portion of the PAP push messages. You need to create an XML file for each of the following
PAP push commands:
• push content (see “pap_push.txt” on page 93 for more information).
• replace content (see “pap_replace.txt” on page 93 for more information).
• push cancellation (see “pap_cancel.txt” on page 94 for more information).
• query push status (see “pap_status.txt” on page 94 for more information).
Note: In the sample pap_push.txt and pap_replace.txt files, you will need to modify all <address> elements to
reflect the desired recipient address(es).
Recipient addresses conform to WAP-PAP 2.0 addressing standards, and have the following format:
WAPPUSH=<email_or_PIN>%3A<port_number>/[email protected]
where <email_or_PIN> is the email address or the PIN of the client and <port_number> is the client port number to
which the message is pushed.
All non-alphanumeric characters other than the plus sign (+), the minus sign (-), the period(.), and the underscore (_)
in <email_or_PIN> must be represented by %<n>, where <n> is the two-digit hexadecimal number representing the
character (for example, %3A represents the colon (:) symbol, while %40 represents the at symbol (@)).
For example, for a push to a handheld with an email address of [email protected] to the port 4567, the PAP
message specifies the address:
WAPPUSH=john.doe%40acme.com%3A4567/[email protected]

2. Deploy the web content and push icons that you want to push to handhelds on a web application server.
3. Place the BrowserChannelPush.java, pappush_browserpush.properties, pap_push.txt, pap_replace.txt,
pap_status.txt, and pap_cancel.txt files into a com\rim\docs\samples\browserpushdemo folder that is in
your CLASSPATH.
4. Edit the pap_browserpush.properties file to specify the location and names of the files to push to the
handheld.

86
7: Writing Mobile Data Service push applications

5. Start Mobile Data Service and handheld simulators.


6. Enable Mobile Data Service push functionality.
7. Compile and run the java file.
In the handheld simulator, the icon that is specified in the unreadIconUrl property appears on the handheld
Home screen. Click the icon to view the web page that is specified in the pushUrlString property.

Delete the channel


If necessary, delete the channel.
1. Edit the pappush_browserpush.properties file.
2. Change the pushType parameter to pushType = Browser-Channel-Delete.
3. Compile and run BrowserChannelPush.java again. The channel icon is removed from the Home screen in the
handheld simulator.

Example: BrowserPushDemo.java (PAP push service implementation)

/*
* BrowserPushDemo.java
* Copyright (C) 2004 Reasearch In Motion Limited. All rights reserved.
* PAP Push properties file
*/
// package com.rim.samples.server.browserpushdemo;

import java.io.*;
import java.net.*;
import java.text.*;
import java.util.*;
import javax.net.ssl.*;
import sun.misc.BASE64Encoder;

/**
* Application which pushes a specified web page to a specified device.
*/
public class BrowserPushDemo {

public static final String CHANNEL = "Browser-Channel";


public static final String MESSAGE = "Browser-Message";
public static final String CONTENT = "Browser-Content";
public static final String CHANNEL_DELETE = "Browser-Channel-Delete";
private static final String PROPERTIES_FILE = "browserpush.properties";

public BrowserPushDemo() { }

/**
* Main method which reads the property file and performs the push.
*/

public static void main(String[] args) {

// Set cases for each potential pap command.


char command = args[0].charAt(0);

87
BlackBerry Wireless Handheld Browser Content Developer Guide

String papFilename;
switch (command)
{
case 'p':
papFilename = "pap_push.txt";
break;
case 's':
papFilename = "pap_status.txt";
break;
case 'c':
papFilename = "pap_cancel.txt";
break;
case 'r':
papFilename = "pap_replace.txt";
break;
default:
System.out.println("invalid command");
return;
}

// Load the properties file.


Properties prop = new Properties();
try {
prop.load(new FileInputStream(PROPERTIES_FILE));
} catch (FileNotFoundException fnfe) {
throw new RuntimeException("property file not found: " + fnfe.getMessage());
} catch (IOException ioe) {
throw new RuntimeException("problems reading property file: " + ioe.getMessage());
}

// Hostname and Port of the Mobile Data Service that will perform the push.
String mdsHostName = prop.getProperty("mdsHostName").trim();
int mdsPort = (new Integer(prop.getProperty("mdsPort").trim())).intValue();

// The URL of the page to push.


String pushUrlString = prop.getProperty("pushUrlString").trim();
String pushType = prop.getProperty("pushType", CHANNEL).trim();
String pushTitle = prop.getProperty("pushTitle", "Push Page").trim();

// URLs of the icons to use for Browser-Channel push type.


String unreadIconUrl = prop.getProperty("unreadIconUrl", "").trim();
String readIconUrl = prop.getProperty("readIconUrl", "").trim();

//Authentication properties.
String user = prop.getProperty("user");
String password = prop.getProperty("password");

// Push security?
boolean useHttps = false;
try {
useHttps = Boolean.valueOf(prop.getProperty("useHttps")).booleanValue();
} catch (Exception e) { }

if (useHttps == true) {
System.setProperty("javax.net.ssl.trustStore",
"C:\\p4\\main\\IPProxyProject\\webserver\\webserver.keystore");
System.setProperty("javax.net.ssl.trustStorePassword", "password");
}

88
7: Writing Mobile Data Service push applications

String pushId = args[1];

String replaceId = "";


if (command == 'r') {
System.out.print("Enter push id to replace: ");
replaceId = (new BufferedReader(new
InputStreamReader(System.in))).readLine().trim();
}

String[] content = null;


if ((command == 'p') || (command == 'r')) {
content = getContent(pushUrlString, pushType, pushTitle, unreadIconUrl,
readIconUrl);
}
// Push the page to the handheld.
int iterations = Integer.parseInt(prop.getProperty("iterations", "1"));
int delay = Integer.parseInt(prop.getProperty("delay", "5"));
String pushIdBase = pushId;
for (int i = 0 ; i < iterations; i++) {
if (i > 0) {
Thread.sleep(delay);
}
if (iterations > 1) {
pushId = pushIdBase + "_" + i;
}
pushPage(command, pushId, replaceId, papFilename, mdsHostName, mdsPort, pushType,
user, password, useHttps, content);
}
}

/*
* A method used to set the push connection and pass push content to
* the Mobile Data Service.
*/
private static String[] getContent(String pushUrlString, String pushType, String
pushTitle, String unreadIconUrl, String readIconUrl) {
String[] content = new String[2];
HttpURLConnection pushConn = null;
URL pushUrl;
StringBuffer contentHeaders = new StringBuffer();
try {
pushUrl = new URL(pushUrlString);
} catch (MalformedURLException e) {
throw new RuntimeException("invalid push URL: " + e.getMessage());
}
pushConn = (HttpURLConnection)pushUrl.openConnection();
pushConn.setAllowUserInteraction(false);
pushConn.setDoInput(true);
pushConn.setDoOutput(false);
pushConn.setRequestMethod("GET");

pushConn.connect();

contentHeaders.append("Content-Location: ").append(pushUrlString);
contentHeaders.append("\r\nX-RIM-Push-Title: ").append(pushTitle);
contentHeaders.append("\r\nX-RIM-Push-Type: ").append(pushType);

89
BlackBerry Wireless Handheld Browser Content Developer Guide

if (pushType.equals(CHANNEL) || pushType.equals(CHANNEL_DELETE)) {
contentHeaders.append("\r\nX-RIM-Push-Channel-ID: ").append(pushUrlString);
if (pushType.equals(CHANNEL)) {
contentHeaders.append("\r\nX-RIM-Push-UnRead-Icon-URL: ").append(unreadIconUrl);
contentHeaders.append("\r\nX-RIM-Push-Read-Icon-URL: ").append(readIconUrl);
}
}

/*
* Read the header properties from the push connection and write
* them to the Mobile Data Service connection.
*/
String name, value;
for (int i = 0; true; i++) {
name = pushConn.getHeaderFieldKey(i);
value = pushConn.getHeaderField(i);
if ((name ==null) && (value == null)) { break; }
if ((name ==null) || (value == null)) { continue; }
if (name.equals("X-RIM-Push-Type")) { continue; }
if (name.equals("Transfer-Encoding")) { continue; }
contentHeaders.append("\r\n").append(name).append(": ").append(value);
}
content[0] = contentHeaders.toString();

/*
* Read content from the push connection and write them to the
* Mobile Data Service connection.
*/
InputStream ins = pushConn.getInputStream();
ByteArrayOutputStream bouts = new ByteArrayOutputStream();
copyStreams(ins, bouts);
ins.close();
content[1] = new String(bouts.toByteArray());

return content;
}

public static void pushPage(char command, String pushId, String replaceId, String filename,
String mdsHostName, int mdsPort, String pushType, String user, String
password, boolean useHttps, String[] content) {

HttpURLConnection mdsConn;
URL mdsUrl;

try {
/* Push listener thread on the device listens to port 7874 for pushes from the
Mobile Data Service. */
String protocol = "http";
if (useHttps == true) {
protocol += "s";
}
mdsUrl = new URL(protocol, mdsHostName, mdsPort, "/pap");
mdsConn = (HttpURLConnection)mdsUrl.openConnection();
if ((user != null) && (password != null)) {
String authString = user + ":" + password;
mdsConn.setRequestProperty("Authorization", "Basic " + new
BASE64Encoder().encode(authString.getBytes()));
}

90
7: Writing Mobile Data Service push applications

String boundary = "";


if ((command == 'p') || (command == 'r')) {
boundary = "asdlfkjiurwghasf";
mdsConn.setRequestProperty("Content-Type", "multipart/related;
type=\"application/xml\"; boundary=" + boundary);
mdsConn.setRequestProperty("X-Wap-Application-Id", "/");
mdsConn.setRequestProperty("X-Rim-Push-Dest-Port", "7874");
}
else {
mdsConn.setRequestProperty("Content-Type", "application/xml");
}

mdsConn.setRequestProperty("Content-Location", pushUrlString);
mdsConn.setRequestProperty("X-RIM-Push-Title", pushTitle);
mdsConn.setRequestProperty("X-RIM-Push-Type", pushType);
if (pushType.equals(CHANNEL) || pushType.equals(CHANNEL_DELETE)) {
mdsConn.setRequestProperty("X-RIM-Push-Channel-ID", pushUrlString);
if (pushType.equals(CHANNEL)) {
mdsConn.setRequestProperty("X-RIM-Push-UnRead-Icon-URL", unreadIconUrl);
mdsConn.setRequestProperty("X-RIM-Push-Read-Icon-URL", readIconUrl);
}
}

try {
mdsConn.setRequestMethod("POST");
} catch (ProtocolException e) {
throw new RuntimeException("problems setting request method: " +
e.getMessage());
}

mdsConn.setAllowUserInteraction(false);
mdsConn.setDoInput(true);
if (!pushType.equals(CHANNEL_DELETE)) {
mdsConn.setDoOutput(true);
OutputStream outs = mdsConn.getOutputStream();
InputStream ins = new BufferedInputStream(new FileInputStream(filename));
ByteArrayOutputStream bouts = new ByteArrayOutputStream();
copyStreams(ins, bouts);
String output = new String(bouts.toByteArray());
output = output.replaceAll("\\$\\(pushid\\)", pushId);
if ((command == 'p') || (command == 'r') {
output = output.replaceAll("\\$\\(boundary\\)", boundary);
output = output.replaceAll("\\$\\(headers\\)", content[0]);
output = output.replaceAll("\\$\\(content\\)", content[1]);
}
if (command == 'r') {
output = output.replaceAll("\\$\\(replaceid\\)", replaceId);
}
output = output.replaceAll("\r\n", "EOL");
output = output.replaceAll("\n", "EOL");
output = output.replaceAll("EOL", "\r\n");
copyStreams(new ByteArrayInputStream(output.getBytes()), outs);
}

mdsConn.connect();

// Output headers returned from mdsConn.


String name, value;

91
BlackBerry Wireless Handheld Browser Content Developer Guide

for (int i = 0; true; i++) {


name = mdsConn.getHeaderFieldKey(i);
value = mdsConn.getHeaderField(i);
if ((name ==null) && (value == null)) { break; }
}

ByteArrayOutputStream output = new ByteArrayOutputStream();


copyStreams(mdsConn.getInputStream(), output);
int rescode = mdsConn.getResponseCode();
if (rescode != HttpURLConnection.HTTP_ACCEPTED) {
throw new RuntimeException("Unable to sent message, received bad response code
from MDS:" + rescode);
}
} catch (IOException e) {
throw new RuntimeException("Unable to send message:" + e.toString());
}
}

/**
* Reads data from the input stream and copies it to the output stream.
*/

private static void copyStreams(InputStream ins, OutputStream outs) throws IOException {


int maxRead = 1024;
byte [] buffer = new byte[1024];
int bytesRead;

for(;;) {
bytesRead = ins.read(buffer);
if (bytesRead <= 0) {break;}
outs.write(buffer, 0, bytesRead);
}
}
}

Example: pap_browserpush.properties file


# pap_browser.properties file

iterations=1
delay=0
debug=true
useHttps = false

# Push from Mobile Data Service simulator on the local computer to handheld simulator.
mdsHostName = localhost

# mdsPort must match WebServer.listen.port set in Mobile Data Service rimpublic.property


file.
mdsPort = 8080

#pushType = Browser-Content
#pushType = Browser-Channel
#pushType = Browser-Channel-Delete
pushType = Browser-Message

92
7: Writing Mobile Data Service push applications

pushTitle = Have a Great Day!

# The actual page (and icons) to push.


pushUrlString = http://localhost/testpage/sample.htm
unreadIconUrl = http://localhost/testpage/smile_unread.png
readIconUrl = http://localhost/testpage/smile.png

# Authentication credentials.
user=pix
password=password

Example: pap_push.txt
--$(boundary)
Content-Type: application/xml; charset=UTF-8

<?xml version="1.0"?>
<!DOCTYPE pap PUBLIC "-//WAPFORUM//DTD PAP 2.0//EN"
"http://www.wapforum.org/DTD/pap_2.0.dtd"
[<?wap-pap-ver supported-versions="2.0"?>]>
<pap>
<push-message push-id="$(pushid)"
deliver-before-timestamp="2005-09-18T19:50:00Z"
ppg-notify-requested-to="http://localhost/
PAPResultNotificationTest.jsp">
<!-- modify address-value attribute as necessary -->
<address address-value="WAPPUSH=recipient1%40pappush.com%3A7874/[email protected]"/
>
<quality-of-service delivery-method="unconfirmed"/>
</push-message>
</pap>
--$(boundary)
$(headers)

$(content)
--$(boundary)--

Example: pap_replace.txt
--$(boundary)
Content-Type: application/xml; charset=UTF-8

<?xml version="1.0"?>
<!DOCTYPE pap PUBLIC "-//WAPFORUM//DTD PAP 2.0//EN"
"http://www.wapforum.org/DTD/pap_2.0.dtd">
<pap>
<push-message push-id="$(pushid)"
replace-push-id="$(replaceid)"
replace-method="pending-only"
ppg-notify-requested-to="http://localhost:8080/
PAPResultNotificationTest.jsp">
<!-- modify address-value attribute as necessary -->
<address address-value="WAPPUSH=recipient2%40pappush.com/[email protected]"/>
<address address-value="WAPPUSH=recipient3%40pappush.com/[email protected]"/>

93
BlackBerry Wireless Handheld Browser Content Developer Guide

<address address-value="WAPPUSH=recipient4%40pappush.com/[email protected]"/>
<quality-of-service delivery-method="preferconfirmed"/>
</push-message>
</pap>
--$(boundary)
$(headers)

$(content)
--$(boundary)--

Example: pap_cancel.txt
<?xml version="1.0"?>
<!DOCTYPE pap PUBLIC "-//WAPFORUM//DTD PAP 2.0//EN"
"http://www.wapforum.org/DTD/pap_2.0.dtd">
<pap>
<cancel-message push-id="$(pushid)">
</cancel-message>
</pap>

Example: pap_status.txt
<?xml version="1.0"?>
<!DOCTYPE pap PUBLIC "-//WAPFORUM//DTD PAP 2.0//EN"
"http://www.wapforum.org/DTD/pap_2.0.dtd">
<pap>
<statusquery-message push-id="$(pushid)"/>
</pap>

Troubleshooting push applications


Push applications identify handhelds based on their email address. If a user stops receiving data from a push
application after switching to a different handheld, the mapping between user’s email address and handheld PIN
might be out-of-date. Verify that the BlackBerry Enterprise Server is operating correctly.
• BlackBerry Enterprise Server for Microsoft Exchange: The Mobile Data Service uses a Database
Consistency tool, dbconsistency.exe, to maintain the mapping between email addresses and handheld PINs.
Administrators can configure the frequency at which this tool runs, and they can also run this tool manually.
See the BlackBerry Enterprise Server for Microsoft Exchange Handheld Management Guide for more
information.
• BlackBerry Enterprise Server for IBM Lotus Domino: An agent synchronizes the BlackBerry Directory with
the BlackBerry Profiles database, in which the email-to-PIN mapping is stored. Administrators can configure
the frequency at which the agent runs. (By default, it runs every 5 minutes.) When multiple BlackBerry
Enterprise Servers are deployed, administrators must set up an appropriate replication schedule so that user
information remains synchronized between each Mobile Data Service in the domain. At a minimum, you

94
7: Troubleshooting push applications

should replicate the BlackBerry Directory Database (bbdir.nsf). See the BlackBerry Enterprise Server for IBM
Lotus Domino Handheld Management Guide for more information.

95
BlackBerry Wireless Handheld Browser Content Developer Guide

96
A
Extensible Hypertext Markup (XHTML)
language reference
XHTML Mobile Profile reference
WAP CSS reference

XHTML Mobile Profile reference


Note: The browser ignores any elements or attributes that are not listed here. Any enclosed text is displayed in normal font, as though
the enclosing tags are not present.

Structural elements
<body>
Indicates the start of the page body content.

Attribute Description
style Specifies an inline style definition.
title Describes the contents of the body element.
background Specifies an image to use as the background.
bgcolor Specifies the background color of the document.
link Specifies the color of text used to indicate text links.
text Specifies the text color used in the document.
xml:lang Declares the human language used by the element.

<head>
Contains information about the current document, such as title, keywords that might be useful to
search engines, and other data that is not considered document content. User agents do not
generally render elements that appear in the head as content. They might, however, make
information in the head available to users through other mechanisms.

Attribute Description
profile Ignored.
BlackBerry Wireless Handheld Browser Content Developer Guide

<html>
The root element of an HTML file.

Attribute Description
version Used for grouping only. Deprecated.
lang Ignored.
xmlns Ignored.

<title>
Provides a descriptive title, which appears at the top of the browser screen. This element must be
enclosed in the <head> tag.

Text and text formatting elements


<abbr>
Specifies that the enclosed text is the abbreviated form of a longer word or phrase. Text appears in
normal font.

<acronym>
Specifies that the enclosed text is an acronym. Text appears in normal font.

<address>
Specifies that the enclosed text is a mailing address. Text appears in normal font.

<b>
Specifies that enclosed text be displayed as bold.

<big>
Renders text in a larger font.

<blockquote>
Specifies that the enclosed text is part of a quotation. Text appears indented by one character space
and appears in normal font.

Attribute Description
cite Provides a URL citation to indicate the source of a quotation. The attribute value should be a URL
enclosed in quotation marks; the URL appears as an underlined link.
lang Ignored.

<br/>
Starts a new line. To be XHTML-MP–compliant, make sure the element is self-closing.

98
A: Extensible Hypertext Markup (XHTML) language reference

<center>
Horizontally centers the enclosed text.

<cite>
Specifies that enclosed text is a citation. Text appears in italic.

<code>
Specifies that enclosed text represents code. Text appears in a fixed-width font.

<dfn>
Specifies that enclosed text is a term definition. Text appears in italic.

<div>
Defines a block of text to which a specific presentation style might be applied.

Attribute Description
align Aligns content according to the align attribute. Only horizontal alignment is supported.
(align=”left”, align=“center”, or align=“right”)

<em>
Renders the enclosed text in italic.

<h1> to <h6>
Indicate a heading. Text in heading elements appears in bold. The <h1> element appears in the
largest font, with the font size decreasing for each successive heading level.

Attribute Description
align Aligns text horizontally. The following values are acceptable:
• align="left"
• align="right"
• align="center"

<hr/>
Renders a horizontal line. To be XHTML-MP–compliant, make sure the element is self-closing.

<i>
Renders the enclosed text in italic.

<kbd>
Represents keyboard input. Text appears in a fixed-width font.

99
BlackBerry Wireless Handheld Browser Content Developer Guide

<p>
Delimits a paragraph of text. Each <p> element starts on a new line.

Attribute Description
align Aligns text horizontally. The following values are acceptable:
• align="left"
• align="right"
• align="center"

<pre>
Formats the enclosed text preserving all spacing and new lines. It does not display text in a fixed-
width font.

<q>
Specifies that enclosed text is a quotation. Text appears in normal font.

Attribute Description
cite Provides a URL citation to indicate the source of a quotation. The attribute value should be a URL
enclosed in quotation marks; the URL appears as an underlined link.

<samp>
Designates enclosed text as sample output from programs, scripts, and so on. Text appears in a
fixed-width font.

<small>
Renders text in a smaller font.

<span>
Delimits an arbitrary portion of content to which to apply style, display, or event management.

<strong>
Specifies that enclosed text be displayed as bold.

<tt>
Specifies the enclosed text as teletype. Text appears in a fixed width font.

<u>
Renders the enclosed text as underlined.

<var>
Indicates a variable name, or a value that the user supplies. Text appears in italic.

100
A: Extensible Hypertext Markup (XHTML) language reference

Link elements
<a>
Indicates an active link.

Attribute Description
href Identifies the target of the link. The following link schemes are supported for the href attribute:
• http://
• mailto:
• tel:
• wtai:
• cti:
• dc:
• PIN:
Text appears as an underlined link. When users select the link, the browser, phone, or messages list
opens.
hreflang Specifies the language of the hyperlink reference.
name Specifies a name for the link. The browser remembers the location as a target for other links.
accesskey Ignored.
charset Specifies the character encoding used in the referenced document; the value must be the name of a
standard character set.
rel Specifies the relationship between the current page and the referenced document. For example,
“stylesheet”.
rev Provides text that describes a link relationship from the referenced target document to the source
document. Not displayed to the user.
style Specifies an inline style definition.
tabindex Ignored.
title Provides a descriptive title for the anchor.
type Specifies the content type of the referenced document; the value is a MIME encoding text, such as
"text/plain".

<link>
Provides an external reference to another document.

Attribute Description
href Specifies the target URL of the resource.
rel Specifies the relationship between the current page and the referenced document. For example,
“stylesheet”.
type Specifies the MIME type of the target URL.

List elements
<dd>
Specifies a definition description. Text appears as a normal paragraph following the <dt> element,
with the left margin indented one space to the right.

101
BlackBerry Wireless Handheld Browser Content Developer Guide

<dl>
Specifies a definition list and encloses one or more <dt> tags.

<dt>
Specifies a definition term. Text appears as a normal paragraph.

<li>
Specifies a list item. These elements appear with a bullet or number, depending on the enclosing
element (<div>, <ul>, or <ol>).

<ol>
Specifies an ordered (numbered) list. One or more <li> elements enclosed in an <ol> element
appear with sequential numbers. The first enclosed <li> element appears on a new line.

<ul>
Specifies an unordered (bulleted) list. One or more <li> elements enclosed in a <ul> element
appear with a bullet. The first enclosed <li> element appears on a new line.

Basic form elements


<form>
Specifies a form that gathers information from the user. Users can submit a form by using the
<submit> input element. After a submission, the form collects the names and values of enclosed
<select>, <input>, and <textarea> elements and submits the query as part of the request (GET)
or as post data (POST).

Attribute Description
action This attribute provides a URI to which the form is submitted; this attribute is required.
method The form query is submitted as part of the GET or POST request.
enctype This attribute is ignored. Form data is encoded with the content type application/x-www-form-
urlencoded.
name Ignored.
style Ignored.
title Ignored.

102
A: Extensible Hypertext Markup (XHTML) language reference

<input/>
Defines a user input object. The browser renders <input> elements according to the value of the
type attribute.

Attribute Description
type The following input types are acceptable:
• type=“checkbox”: The element is rendered using a check box control. Check boxes can occur
anywhere in a form element.
• type=“hidden”: Hidden elements are not displayed, but are included when the form is
submitted.
• type=“password”: The browser displays an asterisk (*) for each character that the user types.
The actual value is included in encoded form data when the form is submitted.
• type=“radio”: The element is rendered using a radio control. Radio input elements can appear
anywhere in a form element.
• type=“reset”: The element appears as a button. Users click the button to reset the form values
to its original values. This does not affect other forms on the screen.
• type=“submit”: The element appears as a submit button.
• type=“text”: The element appears as a text input field.
• type=“img”: The associated image that appears is selectable.
The following input types are not supported:
• type=“file”
• type=“button”
maxlength Sets the maximum number of characters for input elements with type set to password or text.
size Specifies the width of the text field, in characters.
checked Supported if type=“checkbox”. If this attribute is included, the check box appears selected, and the
value of the check box is included when the form is submitted.
name Specifies the name of the check box group; it is required when type=“checkbox”.
value Specifies the value to send to the server if a particular check box is selected when the form is submitted;
it is required when type=“checkbox”.

<label>
Provides a descriptive label for one or more input elements in a form. The label element encloses a
text label and one or more <input> elements. The text label appears in the browser in normal text.

Attribute Description
title The title attribute is ignored.

<option>
Encloses the text of an option in a select list.

Attribute Description
selected Defines the option that is initially selected.

103
BlackBerry Wireless Handheld Browser Content Developer Guide

<select>
Denotes a select list. A select list can be a single-selection or a multiple-selection list. A select list
contains one or more option elements.
With single-selection lists, the option with the selected attribute set is selected by default;
otherwise, the first option in the list is selected by default.
With multiple-selection lists, option elements with the selected attribute set are selected by default;
otherwise, no options are selected.

Attribute Description
multiple Indicates that users are permitted to select more than one option. Rendered as a list of check boxes.

<textarea>
Denotes a multiline text entry field in a form. It can optionally contain plain text, which is displayed
to the user in the text area.

Attribute Description
rows Required. Specifies the vertical dimensions of the text area, in number of characters.
cols Required. Specify the horizontal dimensions of the text area, in number of characters.
name The name attribute provides plain text to display to the user inside the text area.

Basic table elements


<caption>
Provides a description for a table. Enclosed text appears in normal font.

<table>
Specifies the start of a table; it encloses <thead> and <tbody>, or <caption> and <tr>.

Attribute Description
border Specifies the thickness of the border around the outside edges of the table and the inner borders of
the table cells.
cellpadding Specifies the number of pixels of white space to add between cells.
cellspacing Specifies the number of pixels of white space that is rendered between each adjacent cell.
width Sets the width of the table, either in pixels or as a percentage of the browser window.

<td>
Denotes a table cell.

Attribute Description
colspan Specifies the number of columns that the cell should span.
rowspan Specifies the number of rows that the cell should span.
align Specifies the horizontal alignment of the cell content.

104
A: Extensible Hypertext Markup (XHTML) language reference

Attribute Description
width Specifies the width of the cell, either in pixels or as a percentage of the table width.

<th>
Denotes a table heading cell. Text in the cell bold.

<tr>
Denotes a table row.

Attribute Description
align Specifies the horizontal alignment of the row content.

Image elements
<area/>
Defines each area of the image.

Attribute Description
shape Defines the shape of the link area. The following values are acceptable:
• shape=“circle”
• shape=“rect”
• shape=“polygon”
coords This attribute specifies the x and y co-ordinates for the link area. Co-ordinates are comma-delimited.
href This attribute specifies file name and location of the link.

<img/>
Defines an image. Monochrome handhelds support .png and .gif graphics only. With the BlackBerry
Browser, the Mobile Data Service converts .jpeg images to .png format for display on monochrome
handhelds.

Attribute Description
src The browser displays the image that is specified by the src attribute. This attribute is required.
alt Specifies the text that appears when an image is unavailable, provided the browser has been correctly
configured to display it.
usemap Specifies the location of the map element.
height Specifies the height of the image with the unit of measurement. For example, “10pt” or “6px”.
width Specifies the width of the image with the unit of measurement. For example, “10pt” or “6px”.
align Images are aligned horizontally according to the align attribute. The following values are acceptable:
• align=“left”
• align=“right”
Vertical alignment is ignored.

105
BlackBerry Wireless Handheld Browser Content Developer Guide

<map>
Creates an image map.

Attribute Description
name Identifies the image map. The value must match the corresponding usemap value specified for the
image.

Object elements
<object>
The browser supports embedded content such as PME (transcoded SVG) content, MIDI files, and
other HTML pages. The browser does not support embedding of applets. However, the browser only
displays embedded content if it has been properly configured to do so by the end user.

<param>
Defines a parameter for an object.

Meta information
<base>
Specifies an absolute URI that acts as the base URI for resolving relative URIs.

Attribute Description
href Specifies an absolute URI that acts as the base URI for resolving relative URIs.

<meta>
This element provides additional information about the document. If the meta element is included,
the content attribute is required.

Attribute Description
http-equiv Defines the shape of the link area. The following values are acceptable:
• refresh: Redirects the browser to the URL specified by the content attribute.
• expires: Specifies that the browser should remove the page from the cache after the number of
seconds specified by the content attribute.
Note: This tag should be used sparingly for pages intended for wireless browsing because it
increases user traffic on the wireless network and can increase the time it takes to display the page.
• cache-control: Indicates that cache control parameters have been set for the page, specified
by the content attribute.

106
A: Extensible Hypertext Markup (XHTML) language reference

Attribute Description
content Required. Sets the meta information for http-equiv. If:
• http-equiv=“refresh”: Specifies the URL to which the browser is redirected.
• http-equiv=“expires”: Specifies the number of seconds after which the page is removed from
the cache. A value of -1 indicates that the page is not cached, so that the browser requests and
downloads the page every time it is accessed.
• http-equiv=“cache-control”: Specifies how the page ise cached. The following values are
acceptable:
• Public: Page can be stored in public shared caches.
• Private: Page can be stored only in private caches.
• No-cache: Page can not be cached.
• No-store: Page can be cached but not archived.

Script references
<script>
Defines a script, such as a JavaScript.

Attribute Description
type Specifies the MIME type of the script.
language Deprecated.

WAP CSS reference


background
A shorthand property that sets some or all the background properties. Properties can be listed in
any order.
Note: Do not set a background-attachment value unless you are applying background to the <body> element.

Values Description
propert_list Specifies a whitespace-separated list of values for the background-attachment, background-
color, background-image, and background-repeat properties. For example
blockquote {background: red url("images/sand.gif") no-repeat center}
See the descriptions of the background-attachment, background-color, background-
image, and background-repeat properties for more information on valid values.

107
BlackBerry Wireless Handheld Browser Content Developer Guide

background-attachment
For background images that are set behind an entire document, as a property applied to the <body>
element, the background-attachment property determines whether a background image is fixed
and content scrolls across it, or whether the background scrolls with the content.

Values Description
fixed Indicates that the content scrolls, but the background image does not.
scroll Default. Indicates that the background image scrolls with the content.

background-color
Sets the background color of content and padding. If you set a background color, set the foreground
to a contrasting color, so that its content remains visible.

Values Description
color_value Any valid color. A valid color can be specified in the following ways:
• an RGB value (“250,239,111”)
• Hexidecimal notation (“#770aff" or "#70f" (equal to "#7700ff"))
• a valid textual color name (“red”)
transparent Default. Makes the background invisible, enables the color of the parent element to be seen.

background-image
Sets an image as a background pattern.

Values Description
URL Specifies the location of the image to be used for the background pattern.
none Default. No background pattern is used.

background-repeat
Defines whether the background image is repeated (tiled) to fill the display.

Values Description
repeat Default. The background image is tiled both horizontally and vertically.
repeat-x The background image is tiled horizontally and is left-aligned.
repeat-y The background image is tiled vertically and is vertically centered.
no-repeat The background image is not tiled and is vertically centered and left-aligned.

108
A: Extensible Hypertext Markup (XHTML) language reference

border
A shorthand property for setting the width, color, and style of the individual sides of the border.
Properties can be listed in any order.

Values Description
property_list Specifies a whitespace-separated list of values for the border-color, border-style, and
border-width properties. For example:
table {border: red solid thick}
See the descriptions of the border-color, border-style, and border-width properties for
more information on valid values.

border-bottom, border-left, border-right, border-right


Shorthand properties for setting the color, style, and width of the individual sides of the border.
Properties can be listed in any order.

Values Description
property_list Specifies a whitespace-separated list of values for the color, style, and width of the specified side of a
border. For example:
table {border-right: red solid thick}
See the descriptions of the border-color, border-style, and border-width properties for
more information on valid values.

border-bottom-color, border-left color, border-right-color, border-top-color


Sets the color of the individual sides of the border.
Note: You must set a border-style property to solid to display a border.

Values Description
color_value Any valid color. A valid color can be specified in the following ways:
• an RGB value (“250,239,111”)
• Hexidecimal notation (“#770aff" or "#70f", which is equal to "#7700ff")
• a valid textual color name (“red”)
The default is the current foreground color of the element.

border-bottom-style, border-left-style, border-right-style, border-top-style


Sets the style of the individual sides of the border.

Values Description
none Default. The element has no border.
hidden A hidden border is used. Hidden borders have no width and they are ignored by the browser.
solid A solid line is used as a border for the element.

109
BlackBerry Wireless Handheld Browser Content Developer Guide

border-bottom-width, border-left-width, border-right-width, border-top-width


Sets the width of the individual sides of the border.
Note: You must set a border-style property to solid to display a border.

Values Description
width_value Specifies the width of the border. The values for these properties can be any integer with the unit of
measurement. For example, “10pt” or “6px”.
Possible units include em (ems), ex (x-height), px (pixels), in (inches), cm (centimeters), mm
(millimeters), pt (points), and pc (picas).
thin Sets the element border to the browser’s interpretation of a thin width.
medium Default. Sets the element border to the browser’s interpretation of a medium width.
thick Sets the element border to the browser’s interpretation of a thick width.
inherit Indicates that the element inherits the border width of the containing element.

border-color
A shorthand property for setting the color of all four borders.

Values Description
color_value Any valid color. A valid color can be specified in the following ways:
• an RGB value (“250,239,111”)
• Hexidecimal notation (“#770aff" or "#70f", which is equal to "#7700ff")
• a valid textual color name (“red”)
The default is the current foreground color of the element.

border-style
A shorthand property for setting the style of all four borders.

Values Description
none Default. The element has no border.
hidden A hidden border is used. Hidden borders have no width and they are ignored by the browser.
solid A solid line is used as a border for the element.

border-width
A shorthand property for setting the width of all four borders.

Values Description
width_value Specifies the width of the border. The value for this property can be any integer with the unit of
measurement. For example, “10pt” or “6px”.
Possible units include em (ems), ex (x-height), px (pixels), in (inches),
cm (centimeters), mm (millimeters), pt (points), and pc (picas).
thin Sets the element border to the browser’s interpretation of a thin width.
medium Default. Sets the element border to the browser’s interpretation of a medium width.

110
A: Extensible Hypertext Markup (XHTML) language reference

Values Description
thick Sets the element border to the browser’s interpretation of a thick width.
inherit Indicates that the element inherits the border-width property of the containing element.

color
Sets the foreground color. The foreground is the content of the element, typically text, but also the
rule drawn for the <hr/> element, the color of any border (unless you set another color with one of
the border properties), and so on.

Values Description
color_value Any valid color. A valid color can be specified in the following ways:
• an RGB value (“250,239,111”)
• Hexidecimal notation (“#770aff" or "#70f", which is equal to "#7700ff")
• a valid textual color name (“red”)

font
A shorthand property that sets the font-family, font-size, font-style, and font-weight for text.
Properties can be listed in any order.

Values Description
property_list Specifies a whitespace-separated list of values for the font-family, font-size, font-style,
and font-weight properties. For example:
p {font: italic bold "Times New Roman" 10px}
See the descriptions of the font-family, font-size, font-style, and font-weight
properties for more information on valid values.

font-family
Sets a specific or generic font for text.

Values Description
font_name A specific font family name, such as “Arial” or “Times New Roman”. Font names must be enclosed
in quotation marks.
generic_font A font keyword such as serif, sans-serif, cursive, monospace. Generic font keywords should
not be enclosed in quotation marks.
inherit Indicates that the element inherits the font-family property of the containing element.

font-size
Sets the size of a font, either in absolute or relative terms. Relative values are relative to the font size
of the element that contains the current element.

Values Description
size_value Any integer with the unit of measurement. For example, “10pt” or “6px”.
Possible units include em (ems), ex (x-height), px (pixels), in (inches),
cm (centimeters), mm (millimeters), pt (points), and pc (picas).

111
BlackBerry Wireless Handheld Browser Content Developer Guide

Values Description
absolute_size Renders text according to a browser standard.
Possible values include xx-small, x-small, small, medium, large, x-large, xx-large.
relative_size Renders text at a size relative to the standard font size of the element.
Possible values include smaller and larger.
inherit Indicates that the element inherits the font-size property of the containing element.

font-style
Sets the font “style” for text.

Values Description
normal Default. No font style is applied.
italic Uses a font with “italic” in its name or failing that, one with “oblique” in its name. Italic fonts are also
sometimes named “cursive” or “kursive.”
oblique Uses a font with “oblique” in its name or failing that, one with “italic” in its name. Oblique fonts are
also sometimes named “slanted” or “inclined.”
inherit Indicates that the element inherits the font-style property of the containing element.

font-weight
Sets the thickness of the font.
The browser uses a roman font for font-weight values from 100 to 400 and a bold font for values
500 to 900.

Values Description
weight_value Specifies the absolute weight of the font. Possible values include 100 (lightest), 200, 300, 400, 500,
600, 700, 800, 900 (heaviest).
normal Sets the font to standard font weight. Equivalent to 400 on the numerical scale.
bold Sets the font to standard bold weight. Equivalent to 700 on the numerical scale.
bolder Increases the font weight by one level on the numerical scale. If the font already had a weight
equivalent to 900, it remains 900.
lighter Decreases the font weight by one level on the numerical scale. If the font already had a weight
equivalent to 100, it remains 100.
inherit Indicates that the element inherits the font-weight property of the containing element.

height, width
Sets the height/width of the content.

Values Description
measure_value Specifies the height/width. The value of this property can be any integer with the unit of measurement.
For example, “10pt” or “6px”.
Possible units include em (ems), ex (x-height), px (pixels), in (inches),
cm (centimeters), mm (millimeters), pt (points), and pc (picas).
auto Adjusts the height/width of the element to fit the content.
inherit Indicates that the element inherits the height or width property of the containing element.

112
A: Extensible Hypertext Markup (XHTML) language reference

table-layout
Controls the layout of table cells, rows, and columns.

Values Description
fixed Specifies that the width of a cell is fixed to a specified width. In this case, the table layout does not
depend on the content.
For example, if a column is fixed to a width of 25 pts, any line of text that exceeds this length is broken
and continued on a new line.
auto Specifies that the width of the cell is adjusted to the content. In this case, the table layout depends on
the content.
For example, if a line of text is 40 pts in length, the cell is adjusted to a width of 40 pts plus any
specified margin width.
inherit Indicates that the element inherits the table-layout property of the containing element.

text-align
Sets the horizontal alignment of lines of text.

Values Description
left Default. Aligns text to the left margin.
right Aligns text to the right margin.
center Centers the text in the display.
inherit Indicates that the element inherits the text-align property of the containing element.

text-decoration
Sets underlining and blinking of text.

Values Description
none Default. No text decoration is applied.
underline Underlines the text.
blink Causes the text to blink.
inherit Indicates that the element inherits the text-decoration property of the containing element.

-wap-input-format
Sets an input mask for text input in a form.
To limit the number of characters users can type, specify a single-digit number before the character
tag. For example, “3X” requires the user to type a maximum of three symbolic, numeric, or
uppercase alphabetic characters.
To enable users to type an unlimited number of characters, specify an asterisk (*) before the
character tag. For example, “*a” enables the user to type any number of symbolic or lowercase
alphabetic characters.

113
BlackBerry Wireless Handheld Browser Content Developer Guide

To insert a character into the mask, use the syntax \c, replacing the c with the character that you
want to insert. This is useful for inserting, for example, a dash in a nine-digit area code.

Values Description
A Any symbolic or uppercase alphabetic character (no numbers).
a Any symbolic or lowercase alphabetic character (no numbers).
N Any numeric character (no symbols or alphabetic characters).
X Any symbolic, numeric, or uppercase alphabetic character (not changeable to lowercase).
x Any symbolic, numeric, or lowercase alphabetic character (not changeable to uppercase).
M Default. Any symbolic, numeric, or uppercase alphabetic character (changeable to lowercase). For
multiple character input, the user input automatically defaults to an uppercase first character.
m Any symbolic, numeric, or lowercase alphabetic character (changeable to uppercase). For multiple
character input, the user input automatically defaults to a lowercase first character.

-wap-input-required
Requires a user to type text, click a button, or click a menu item on a form.

Values Description
True Specifies that the user is required to supply input.
False Specifies that the user is not required to supply input.

-wap-marquee-dir
Controls whether content scrolls from left to right (ltr) or from right to left (rtl).
Note: This property requires that the selected element also has the display property set to the -wap-marquee value.

Values Description
ltr Scrolls content from left to right.
rtl Scrolls content from right to left.

-wap-marquee-loop
Controls how many times the marquee effect repeats.
Note: This property requires that the selected element also has the display property set to the -wap-marquee value.

Values Description
iterations Indicates the number of iterations the marquee effect performs. The value can be any integer. Setting
this value to 0 has the same effect as not setting the display property to
-wap-marquee.
infinite The marquee effect loops indefinitely.

114
A: Extensible Hypertext Markup (XHTML) language reference

-wap-marquee-speed
Controls the speed of the marquee effect.
Note: This property requires that the selected element also has the display property set to the -wap-marquee value.

Values Description
slow Scrolls text across the screen slowly.
normal Scrolls text across the screen at the standard scroll rate.
fast Scrolls text across the screen quickly.

-wap-marquee-style
Controls how content scrolls across the screen.
Note: This property requires that the selected element also has the display property set to the -wap-marquee value.

Values Description
scroll The content starts completely off one side of the screen and then scrolls across the screen until its
completely off the other side of the screen, then repeats.
slide The content starts completely off one side of the screen and then scrolls across the screen. Scrolling
stops when the first character reaches the other side of the screen.
alternate The content starts completely off one side of the screen, scrolls across the screen until its completely
off the other side of the screen, and then does the same thing in the reverse direction, then repeats.

115
BlackBerry Wireless Handheld Browser Content Developer Guide

Element/CSS property matrix


CSS Property XHTML tag

<blockquote>

<h1> to <h6>
<fieldset>
<button>

<center>

<legend>
<blink>

<input>
<body>

<cite>

<code>

<font>

<form>
<big>

<dfn>

<dir>

<div>

<img>

<kbd>
<dd>

<dt>

<em>

<li>
<a>

<b>

<i>
background a
background-attachment a
background-color a a a a a a a b a a a a a a a a a a a a a a a a a
background-image a
background-repeat a
border a a a
border-bottom a a a
border-bottom-color a a a
border-bottom-style a a a
border-bottom-width a a a
border-color a a a
border-left a a a
border-left-color a a a
border-left-style a a a
border-left-width a a a
border-right a a a
border-right-color a a a
border-right-style a a a
border-right-width a a a
border-style a a a
border-top a a a
border-top-color a a a
border-top-style a a a
border-top-width a a a
border-width a a a
color a a a a a a a a a a a a a a a a a a a a a a a a a
font a a a a a a a a a a a a a a a a a a a a a a a a a
font-family a a a a a a a a a a a a a a a a a a a a a a a a a
font-size a a a a a a a a a a a a a a a a a a a a a a a a a
font-style a a a a a a a a a a a a a a a a a a a a a a a a a
font-weight a a a a a a a a a a a a a a a a a a a a a a a a a
height a a 1
table-layout
text-align a a a a a a a a a a a a a a a a a a a a a a a
text-decoration a a a a a a a a a a a a a a a a a a a a a a a a a
width a a 1
-wap-input-format 2
-wap-input-required 2
-wap-marquee-dir a
-wap-marquee-loop a
-wap-marquee-speed a
-wap-marquee-style a

1
Applies only to <input> elements where type is one of “button”, “submit”, or “reset”.
2
Applies only to <input> elements where type=“text”.

116
A: Extensible Hypertext Markup (XHTML) language reference

Element/CSS property matrix (continued)


CSS Property XHTML tag

<optgroup>

<textarea>
<marquee>

<option>

<select>

<strike>

<strong>
<small>

<table>
<menu>

<samp>

<span>
<pre>

<sub>

<sup>

<var>
<ol>

<td>

<th>

<tr>

<tt>

<ul>
<p>

<s>

<u>
background a a a a
background-attachment
background-color a a a a a a a a a a a a a a a a a a a a a a a a a
background-image a a a a
background-repeat a a a a
border a a a a a
border-bottom a a a a a
border-bottom-color a a a a a
border-bottom-style a a a a a
border-bottom-width a a a a a
border-color a a a a a
border-left a a a a a
border-left-color a a a a a
border-left-style a a a a a
border-left-width a a a a a
border-right a a a a a
border-right-color a a a a a
border-right-style a a a a a
border-right-width a a a a a
border-style a a a a a
border-top a a a a a
border-top-color a a a a a
border-top-style a a a a a
border-top-width a a a a a
border-width a a a a a
color a a a a a a a a a a a a a a a a a a a a a a a a a
font a a a a a a a a a a a a a a a a a a a a a a a a a
font-family a a a a a a a a a a a a a a a a a a a a a a a a a
font-size a a a a a a a a a a a a a a a a a a a a a a a a a
font-style a a a a a a a a a a a a a a a a a a a a a a a a a
font-weight a a a a a a a a a a a a a a a a a a a a a a a a a
height
table-layout a
text-align a a a a a a a a a a a a a a a a a a a a a a
text-decoration a a a a a a a a a a a a a a a a a a a a a a a a a
width a a a
-wap-input-format a
-wap-input-required a
-wap-marquee-dir a
-wap-marquee-loop a
-wap-marquee-speed a
-wap-marquee-style a

117
BlackBerry Wireless Handheld Browser Content Developer Guide

118
B
Wireless Markup Language (WML) reference
WML reference

WML reference
The following table summarizes browser support for each WML element and its attribute(s). The browser
supports WML 1.3.

Structure elements
<access>
If specified, the browser compares the <access> element to the domain and path that are specified
in the <access> element to determine whether the user has the proper access to display the page. If
not, the browser displays an error message.

Attribute Description
domain Specifies the domain used to verify access privileges.
path Specifies the path used to verify access privileges.

<card>
Contains the entire card.

Attribute Description
title Displays the card title in the Title area of the screen.
newcontext If set to true, this attribute clears the variable in store.
ordered Ignored. All elements in a page are rendered.
onenterforward Opens the specified URL when the card is accessed using a <go> task.
onenterbackward Opens the specified URL when the card is accessed using a <prev> task.
ontimer Opens the specified URL when the timer has expired.

<head>
A container element for information on access control that applies to the entire deck (the collection
of all cards). See the <access> element.

<meta>
Not supported. The browser ignores any <meta> tags.
BlackBerry Wireless Handheld Browser Content Developer Guide

<template>
Specifies deck-level <do> or <onevent> items. These items are included in every card for the deck,
unless the card has a more specific <do> or <onevent> element that shadows those in the template.
The browser handles template attributes as though they are <onevent> definitions for the
corresponding events.

Attribute Description
onenterforward Treated as an onenterforward <onevent> element with a <go> action.
onenterbackward Treated as an onenterbackward <onevent> element with a <go> action.
ontimer Treated as an ontimer <onevent> element with a <go> action.

<wml>
Defines a wml deck.

Text and text formatting elements


<b>
Renders text in bold in the current font and size, if available. Otherwise, the standard font is used.

<big>
Renders text in the next larger size of the current font, if available. Nesting of <big> and <small>
elements is respected.

<br>
Starts a new line.

<p>
Denotes a new paragraph and renders content according to the attributes.
For layout purposes, the <p> and <br/> elements are the same.

Attribute Description
align Specifies the position of the contents of the <p> element on screen.
mode Ignored. Content is always wrapped.

<em>
Renders text in italic in the current font, if available. Otherwise, the standard font is used.

<i>
Renders text in italic in the current font and size, if available. Otherwise, the standard font and size
is used.

120
B: Wireless Markup Language (WML) reference

<pre>
Not supported.

<small>
Renders text in the next smaller size of the current font, if available. The browser supports nesting of
big and small elements.

<strong>
Renders text in the bold font of the current size, if available. Otherwise, the standard font is used.

<u>
Underlines content enclosed in the <u> element in the current font and size, if available. Otherwise,
the standard font and size are used.

Link elements
<a>
Specifies a link to follow.

Attribute Description
href Specifies the target of the link. The browser substitutes any variable references from the WAP context.
title Ignored.
accesskey Ignored.

<anchor>
When the user moves the cursor over a character or image that is contained in the <anchor>
element, users can click the Follow Link menu item to perform the <go>, <prev>, or <refresh> task
that is associated with the <anchor> element.

Attribute Description
domain Specifies the domain used to verify access privileges.
path Specifies the path used to verify access privileges.

Table elements
<table>
Denotes a new table.

Attribute Description
title Ignored.

121
BlackBerry Wireless Handheld Browser Content Developer Guide

align Aligns the text in table columns according to the align value. This attribute is optional. The content of
each cell is left-aligned by default.
For example, align="LCR". Content in the first column is left-justified; content in the second column
is centered; and content in the third column is right-aligned.
columns Required. Specifies the number of columns in the table.

<tr>
Denotes a new table row.

<td>
Denotes a new table cell.

Image elements
<img>
Defines an image. When images are contained in <anchor> or <a> elements, users can select the
image.

Attribute Description
alt Specifies the text that appears when an image is unavailable, provided that the browser has been
correctly configured to display it. When the real image arrives, the real image replaces the alt
placeholder.
src Specifies the location of the image on the server.
localsrc Unsupported. The browser does not support <localsrc> images.
vspace Specifies the amount of white space to insert above and below the image.
hspace Specifies the amount of white space to insert to the left and right of the image.
align Not supported. Each image is displayed on its own line.
height Specifies the image height.
width Specifies the image width.

Event elements
<do>
Defines an event trigger. The <do> element can enclose the following task elements: <go>, <prev>,
<noop>, or <refresh>.

122
B: Wireless Markup Language (WML) reference

In the browser, <do> elements that are defined on a card appear both as menu items on the browser
menu and as “soft keys" in a non-scrolling area at the bottom of the screen.

Attribute Description
type Required. Specifies the type of <do> element. The <do> element type can be one of accept, help,
or prev. A <do> element of type accept appears first on the menu.
The type attribute also matches <do> elements in the deck template, when the name attribute is not
defined, for shadowing purposes.
label Specifies the label used for the associated menu item. If a label attribute is not included, a default name
is assigned to the menu item based on type.
name Matches <do> elements in the deck template for shadowing purposes.
optional <do> elements with the optional attribute set appear after other <do> elements on the menu.

<onevent>
Specifies how events are handled.

Attribute Description
type Required. Identifies the event to handle; it also matches <do> elements in the deck template for
shadowing.
The type attribute can have one of the following values:
• onenterbackward: Occurs when a user navigates backward to a card.
• onenterforward: Occurs when a user navigates forward to a card.
• onpick: Occurs when a user selects or clears an option.
• ontimer: Occurs when the timer, specified by the <timer> element, expires.
id Sets a unique name for the element.

<postfield>
Specifies name/value pairs that are included in the HTTP request. <postfield> elements must be
enclosed in a <go> element. Variable references in the name and value attributes of each
<postfield> element are replaced with appropriate values from the WAP context.

Attribute Description
name Required. Specifies the name of the variable to be passed to the server.
value Required. Specifies the value of the variable to be passed to the server.
id Sets a unique name for the element.

123
BlackBerry Wireless Handheld Browser Content Developer Guide

Task elements
<go>
Directs the browser to a specified URI. The browser sets any variables that are specified in <setvar>
elements within the <go> element, and includes any values that are specified in contained
<postfield> elements.

Attribute Description
href Specifies the target URI that the browser goes to.
sendreferer Specifies whether the URI is sent in the request. Valid values are yes or no.
method Specifies the request type. The browser supports both the GET and the POST methods of
sending requests.
enctype Ignored. The browser uses the default: application/x-www-form-urlencoded.
cache-control Forces page retrieval from the network instead of the cache. If this attribute is set to no-cache, a
flag is set on the request being sent to invalidate this page in the cache, if it is there, before
retrieving the page.
accept-charset Ignored. The browser uses the default: UTF-8.

<noop>
Specifies whether the browser effectively removes any <do> or <onevent> elements from the current
card.

<prev>
Directs the browser to a specified URI. The inclusion of the <prev> element in <do> elements affects
menu construction. The browser menu always contains at least one item that enables users to go
back in the navigation history.
If the current card does not contain any <do> elements with a <prev> task, by default the browser
creates a Back menu item. If the current card contains one or more <do> elements that contain
<prev> elements, the browser does not create a separate menu item and relies on the <do> elements
for that card to provide this behavior instead.

<refresh>
Refreshes any variables that are specified by the enclosed <setvar> element(s). If an event occurs
that has a <refresh> task, the browser first sets any variables that are specified in <setvar>
elements that are contained in the <refresh> element. It then refreshes the current page using the
updated WAP context.

124
B: Wireless Markup Language (WML) reference

Input elements
<fieldset>
Ignored. Enclosed elements are rendered as through the <fieldset> element did not exist.

<input>
Renders as a text field into which users can type text. If users type a value that is not consistent
with the restrictions specified by the attributes in the input element, the browser displays a warning
when users try to save the value.
Input boxes appear on a separate line from the surrounding text.

Attribute Description
name Specifies the name of the variable to set with any typed value.
type Specifies the type of information being collected. Valid values include text or password. If type is
set to password, the browser displays an asterisk (*) for each character that the user types.
value Specifies the initial value that is displayed in the input field when the card is first rendered. This value
is used only when the variable specified by the name attribute is not set already in the WAP Context.
If the variable is set, the current value of that variable is used instead.
format Specifies a mask. The browser checks that any text the user enters in the input field conforms to the
mask that is specified by this attribute. The following character tags define which characters can be
typed:
• A — Any symbolic or uppercase alphabetic character (no numbers).
• a — Any symbolic or lowercase alphabetic character (no numbers).
• N — Any numeric character (no symbols or alphabetic characters).
• X — Any symbolic, numeric, or uppercase alphabetic character (not changeable to lowercase).
• x — Any symbolic, numeric, or lowercase alphabetic character (not changeable to uppercase).
• M — Default. Any symbolic, numeric, or uppercase alphabetic character (changeable to lowercase).
For multiple character input, the user input autmatically defaults to an uppercase first character.
• m — Any symbolic, numeric, or lowercase alphabetic character (changeable to uppercase). For
multiple character input, the user input autmatically defaults to a lowercase first character.
Tips:
• To limit the number of characters users can type, specify a single-digit number before the character
tag. For example, “3X” requires the user to type a maximum of three symbolic, numeric, or
uppercase alphabetic characters.
• To enable users to type an unlimited number of characters, specify an asterisk (*) before the
character tag. For example, “*a” enables the user to type any number of symbolic or lowercase
alphabetic characters.
• To insert a character into the mask, use the syntax \c, replacing the c with the character that you
want to insert. This is useful for inserting, for example, a dash in a nine-digit area code.
emptyok Enables the user to leave the field blank.
size Specifies the size, in characters, of the input box.
maxlength Specifies the maximum length of text the user can type.
tabindex Ignored. Tabbing is not supported.

125
BlackBerry Wireless Handheld Browser Content Developer Guide

<optgroup>
Ignored. Options in a <select> element are rendered as a flat list on the screen.

<option>
Specifies an item in a <select> list. <option> elements are rendered in the manner specified by the
enclosing <select> list.

Attribute Description
value Specifies the value of the enclosing <select> variable, if the <select> element has a NAME
attribute.
title Ignored.
onpick Specifies the URI that the browser loads when the option is selected.

<select>
Presents a list to the user. Users can select one or more of the options.
Select lists are fully displayed on every card. Users can scroll through options. Single-selection lists
are rendered as radio buttons. Multiple-selection lists are rendered as check boxes.
See the <option> element for more information.

Attribute Description
title Ignored.
name Specifies the name of the variable that is set with the selection.
value Sets the default value of the variable.
iname Specifies the variable to be set with the (1-based) index of the selected option, according to the
specifications.
ivalue Sets the index(es) of the preselected option(s). Use this attribute only if the variable specified by iname
does not already have a value.
multiple Specifies whether the <select> element is rendered as a multiple-selection list with a set of check
boxes.
tabindex Ignored. Tabs are not supported.

Variable elements
<setvar>
Specifies a new value for a given variable in the WAP context. When a <go>, <prev>, or <refresh>
task is performed, the browser first looks for any associated <setvar> elements and then updates
the WAP context accordingly before running the task.

Attribute Description
name Sets the name of the variable.
value Sets the value of the variable.

126
B: Wireless Markup Language (WML) reference

<timer>
Specifies a timer for the current card. The browser implements card timers according to the WML
specifications. In particular, a <refresh> operation stops the timer, sets its corresponding variable to
the current timer value, performs the refresh, and then resets the timer and restarts it.
When the timer expires, the variable that is specified by the name attribute is set to 0 before any
<ontimer>tasks are run.

Attribute Description
name Specifies the variable name to be set with the timer value for card entry, exit, and timer-expire events.
value Specifies the initial timer value for on-card entry events.

127
BlackBerry Wireless Handheld Browser Content Developer Guide

128
C
JavaScript language reference
Using JavaScript
Supported JavaScript objects

Using JavaScript
The BlackBerry device browser supports JavaScript 1.0, 1.1, 1.2, 1.3, and small subsets of JavaScript 1.4 and 1.5.
Note: JavaScript is only supported on handhelds with at least 16 MB of memory.

The browser also supports the ECMA-262 ECMAScript Language Specification.


The browser processes JavaScript that is run when the page is first rendered and JavaScript that is associated with
control actions on the page. The JavaScript support handles any additional HTML and JavaScript content that the
JavaScript produces and reads any auxiliary JavaScript support libraries that are referenced from the page.
Note: The BlackBerry device browser does not support style sheets for Dynamic HTML. Any JavaScript on the page that creates Dynamic
HTML effects (for example, pop-up menus) runs, but has no visual effect, and might not be fully functional. The JavaScript support is
provided for pages for which HTML content is partially or fully generated by JavaScript and for data processing operations that are
coded in JavaScript, such as input field validation in forms and processing "Login" buttons on various sites.

On the BlackBerry device browser, users can enable or disable JavaScript. JavaScript can also be disabled through
an IT policy.
See “Scripting Basics” on page 197 for information on JavaScript reserved words and supported statements, and
operators and expressions.
Additional JavaScript resources can be found on the Internet.

Supported JavaScript objects


The following JavaScript objects are supported by the BlackBerry device browser.

Object Summary See page


BlackBerry The BlackBerry object defines the network read-only property, which is used to define the network on 131
which the BlackBerry communicates.
Properties location network

Methods —
BlackBerry Wireless Handheld Browser Content Developer Guide

Object Summary See page


Blackberry Location The BlackBerry Location object is designed to provide access to Global Positioning System (GPS) location 132
of the BlackBerry device. The GPS location refers to the geographical co-ordinates, latitude and longitude,
of the BlackBerry device.
Properties GPSSupported latitude longitude

Methods onLocationUpdate() refreshLocation() setAidMode()

Navigator The Navigator object is designed to return information about the version of the BlackBerry Browser that 136
is being used. All its properties, which are read-only, contain information about different aspects of the
browser.
Properties appCodeName language plugins
appName mimeTypes userAgent
appVersion platform

Methods javaEnabled() preferences() taintEnabled()


plugins.refresh() savePreferences()

Document The Document object provides access to the elements in an HTML page from within your script. This 142
includes the properties of every form, link, and anchor (and, where applicable, any subelements), as well
as global document properties such as background and foreground colors.
Properties alinkColor fgColor plugins
anchors formName referrer
applets forms tags
bgColor height title
classes ids URL
cookie images vlinkColor
domain lastModified width
embeds linkColor

Methods captureEvents() handleEvent() write()


close() open() writeln()
contextual() releaseEvent()
getSelection() routeEvent()

Form The Form object enables you to access the elements of an HTML form that is used to collect information 150
from users.
Properties action length target
elements method
encoding name

Methods handleEvent() reset() submit()

Event Handlers onClick onReset onSubmit

Screen The Screen object returns information about the dimensions and color depth of the handheld display. 150
Properties availHeight availWidth pixelDepth
availLeft colourDepth width
availTop height

Methods —

130
C: JavaScript language reference

Object Summary See page


Window The Window object is created automatically when the browser encounters a <body> or <frame> tag, 160
and returns information about the window.
Properties blackberry locationbar screenx
closed menubar screenY
crypto name scrollbars
defaultStatus offscreenBuffering self
document opener status
frames outerHeight statusbar
history outerWidth toolbar
location pageXOffset top
innerHeight pageYOffset window
innerWidth parent
length personalbar

Methods alert() find() resizeTo()


atob() focus() routeEvent()
back() forward() scroll()
blur() handleEvent() scrollBy()
btoa() home() scrollTo()
captureEvents() moveBy() setHotKeys()
clearInterval() moveTo() setInterval()
clearTimeout() open() setTimeout()
close() print() setZOptions()
confirm() prompt() stop()
disableExternalCapture() releaseEvents()
enableExternalCapture() resizeBy()

BlackBerry
The BlackBerry object defines the network read-only property, which is used to define the network on which the
BlackBerry communicates.

Member type Member name Notes See page


Properties location read-only 132
network read-only 132

location
Acts a pointer to the blackberry.location object. This property is only supported by BlackBerry
devices running version 4.1 of the BlackBerry device software. This property is read-only.
Syntax blackberry.location

Parameters none
Returns A pointer to the blackberry.location object.

131
BlackBerry Wireless Handheld Browser Content Developer Guide

Example The following code fragment displays the current geographic co-ordinates of the
BlackBerry device:
document.write("The client BlackBerry device is currently
located at " + blackberry.location.latitude +
" degrees latitude and " +
blackberry.location.longitude +
" degrees longitude.");

See also • blackberry.location.GPSSupported


• blackberry.location.latitude
• blackberry.location.longitude
• blackberry.location.onLocationUpdate()
• blackberry.location.refreshLocation()
• blackberry.location.setAidMode()

network
Identifies the wireless network on which the handheld is communicating. This property is read-only.
Syntax blackberry.network

Parameters none
Returns A string identifying one of the following networks: Mobitex®, GPRS, CDMA, iDEN.
Example The following code fragment displays the value of network:
document.write("The client BlackBerry device is communicating
on the " + blackberry.network + " wireless
network.");

See also • window.blackberry

BlackBerry Location
The BlackBerry Location object is designed to provide access to Global Positioning System (GPS) location of the
BlackBerry device. The GPS location refers to the geographical co-ordinates, latitude and longitude, of the
BlackBerry device.

Member type Member name Notes See page


Properties GPSSupported read-only 132
latitude read-only 136
longitude read-only 137
Methods onLocationUpdate() 134
refreshLocation() 134
setAidMode() 135

132
C: JavaScript language reference

GPSSupported
Returns whether or not the BlackBerry device supports GPS. This property is read-only.
Syntax blackberry.location.GPSSupported

Parameters none
Returns • Boolean true if the BlackBerry device supports GPS.
• Boolean false if the BlackBerry device does not support GPS.
Example The following code determines whether GPS is supported, then sets the GPS
location aid mode and refreshes the location:
if(blackberry.location.GPSSupported) {
blackberry.location.setAidMode(0);
blackberry.location.refreshLocation();
}

See also • blackberry.location

latitude
Provides the current latitude of the BlackBerry device. To ensure that the most accurate co-ordinate
is returned, you should call refreshLocation() first. This property is read-only.
Syntax blackberry.location.latitude

Parameters none
Returns The current latitude, in degrees, of the BlackBerry device. Positive values indicate
northern latitude; negative values indicate southern latitude.
Example The following code fragment displays the current geographic co-ordinates of the
BlackBerry device:
document.write("The client BlackBerry device is currently
located at " + blackberry.location.latitude +
" degrees latitude and " +
blackberry.location.longitude +
" degrees longitude.");

See also • blackberry.location


• blackberry.location.longitude

longitude
Provides the current longitude of the BlackBerry device. To ensure that the most accurate co-
ordinate is returned, you should call refreshLocation() first. This property is read-only.
Syntax blackberry.location.longitude

Parameters none

133
BlackBerry Wireless Handheld Browser Content Developer Guide

Returns The current longitude, in degrees, of the BlackBerry device. Positive values indicate
eastern longitude; negative values indicate western longitude.
Example The following code fragment displays the current geographic co-ordinates of the
BlackBerry device:
document.write("The client BlackBerry device is currently
located at " + blackberry.location.latitude +
" degrees latitude and " +
blackberry.location.longitude +
" degrees longitude.");

See also • blackberry.location


• blackberry.location.latitude

onLocationUpdate()
Registers a callback method that is called when the location is updated using refreshLocation().
Syntax blackberry.location.onLocationUpdate(method)

Parameters method A supported JavaScript method.


Example The following code fragment displays an alert to the user when the location is
updated informing them of the updated location.
blackberry.location.onLocationUpdate(window.alert("Your new
position is " + blackberry.location.latitude +
" degrees latitude and " +
blackberry.location.longitude +
" degrees longitude."));

See also • blackberry.location

refreshLocation()
Requests an update of the BlackBerry device’s location.
Syntax blackberry.location.refreshLocation

Parameters none
Returns A string containing the current latitude and longitude, in degrees, of the BlackBerry
device.
Example The following code determines whether GPS is supported, then sets the GPS
location aid mode and refreshes the location:
if(blackberry.location.GPSSupported) {
blackberry.location.setAidMode(0);
blackberry.location.refreshLocation();
}

See also • blackberry.location

134
C: JavaScript language reference

setAidMode()
Specifies which method the BlackBerry device will use to obtain the GPS location. There are three
ways the device can obtain location information.

Aid Mode Description


Cellsite This method uses the GPS location of the active cellsite tower to provide first order GPS information. It
provides the least accurate location information; however, it is the fastest location mode.
Note: This location method requires network connectivity and carrier support.
Assisted This method uses the network to provide ephemeris satellite data to the device chip. It provides the GPS
location faster than the autonomous mode and more accurately than the cellsite mode.
Note: This location method requires network connectivity and carrier support.
Autonomous This method uses the GPS chip on the BlackBerry device without assistance from the network. The
autonomous mode provides the first GPS location the slowest.

Syntax blackberry.location.setAidMode(aidMode)

Parameters aidMode Identifies the method used to obtain GPS location. The value for this
parameter may be one of:
• 0: Cellsite
• 1: Assisted
• 2: Autonomous
Example The following code determines whether GPS is supported, then sets the GPS
location method and refreshes the location:
if(blackberry.location.GPSSupported) {
blackberry.location.setAidMode(0);
blackberry.location.refreshLocation();
}

See also • blackberry.location

135
BlackBerry Wireless Handheld Browser Content Developer Guide

Navigator
The Navigator object is designed to return information about the version of the BlackBerry Browser that is being
used. All its properties, which are read-only, contain information about different aspects of the browser.

Member type Member name Notes See Page


Properties appCodeName read-only 132
appName read-only 136
appVersion read-only 137
language read-only 137
mimeTypes read-only 139
platform Treated as a contant. Returns "BlackBerry." —
plugins Provides a list of the plug-in objects installed on the client browser. —
userAgent read-only 141
Methods javaEnabled() — 137
plugins.refresh() Stub implementation. This method has no effect. —
preferences() — 139
savePreferences() Stub implementation. This method has no effect. —
taintEnabled() — 140

appCodeName
Provides the application code name. This property is read-only.
Syntax navigator.appCodeName

Parameters none
Returns A string specifying the code name of the browser. The value could depend on the
emulation mode.
Example The following code fragment displays the value of the appCodeName property:
document.write("The code name of this application is " +
navigator.appCodeName);

appName
Provides the name of the client browser. This property is read-only.
Syntax navigator.appName

Parameters None
Returns A string that specifies the name of the browser. In the case of the handheld, the
value is always "BlackBerry."

136
C: JavaScript language reference

Example The following code fragment displays the value of the appName property, which, in
the case of the handheld, will be BlackBerry:
document.write("The name of the client browser is " +
navigator.appName);

appVersion
Provides the version of the BlackBerry Browser.
This property is read-only.
Syntax navigator.appVersion

Parameters none
Returns A string that contains the version of the BlackBerry Browser (for example, "4.1.0").
Example The following code fragment displays version information for the Navigator:
document.write("The version of the BlackBerry Browser is " +
navigator.appVersion);

javaEnabled()
Tests whether or not Java is enabled.
Syntax navigator.javaEnabled()

Parameters none
Returns In the case of the BlackBerry Browser, always returns true.
Example The following code fragment runs the function doThis if Java is enabled; otherwise,
it runs the function doThat:
if (navigator.javaEnabled()) {
doThis();
}
else doThat();

language
Provides the two-letter language code that represents the default language translation of the
browser.
This property is read-only.
Syntax navigator.language

Parameters none
Returns A string that contains the two-letter language code (For example, "en").

137
BlackBerry Wireless Handheld Browser Content Developer Guide

Example The following code fragment displays the value of the language property:
document.write("The default language translation of the client
browser is " + navigator.language);

mimeTypes
Provides the MIME types supported by the client.
This property is read-only.
Syntax • navigator.mimeTypes[index]
• navigator.mimeTypes.length

Parameters index An integer that represents a MIME type contained in the array.
Properties length Specifies the number of MIME types that are supported by the
client.
Returns An array of supported MIME types.
Example The following code fragment displays the type, description, and suffixes properties
for each supported mime type on a client:
for (i=0; i < navigator.mimeTypes.length; i++) {
document.writeln("<TR VALIGN=TOP><TD>",i,"</TD>",
"<TD>",navigator.mimeTypes[i].type,"</TD>",
"<TD>",navigator.mimeTypes[i].desc,"</TD>",
"<TD>",navigator.mimeTypes[i].suffixes,"</TD>");
}

138
C: JavaScript language reference

plugins.refresh()
Syntax navigator.platform

Parameters none
Returns A string indicating the platform on which the browser is running. In the case of the
handheld, the value will always be "BlackBerry".
Example The following code fragment displays the value of the platform property, which, in
the case of the handheld, will be BlackBerry:
document.write("The name of the client browser is " +
navigator.platform):

Syntax navigator.plugins

Parameters None
Returns A string that specifies the name of the browser. In the case of the handheld, the
value is always "BlackBerry."
Example The following code fragment displays the value of the appName property, which, in
the case of the handheld, will be BlackBerry:
document.write("The name of the client browser is " +
navigator.appName):

Makes newly installed plugins available and updates relevent arrays such as the plugins array.
Syntax navigator.plugins.refresh(true|false)

Parameters true The method reloads all open documents that contain embedded
objects
false All open documents are not reloaded.
Returns An empty array.
Example The following code fragment refreshes arrays and reloads open documents that
contain embedded objects:
navigator.plugins.refresh(true);

preferences()
Queries the preferences of the handheld.
Syntax navigator.preferences(prefName[, setValue])

139
BlackBerry Wireless Handheld Browser Content Developer Guide

Parameters prefName The name of the preference whose value you want to retrieve. Valid
names include:
• general.always_load_images
• security.enable_java
• javascript.enabled
• browser.enable_style_sheets
• autoupdate.enabled
• network.cookie.cookieBehavior
• network.cookie.warnAboutCookies

setValue This parameter is not supported by the handheld browser.


Returns The value of the specified preference.
Example The following code fragment creates an image link if images are always loaded,
otherwise it creates text link:
If (navigator.preferences(general.always_load_images)) {
document.writeln("<a href=\"www.blackberry.com\">
<img src=\"bb_logo.gif\"></a>");
{
else {
document.writeln("<a href=\"www.blackberry.com\">
www.blackberry.com</a>");
{

taintEnabled()
Syntax navigator.savePreferences()

Parameters None
Returns A string that specifies the name of the browser. In the case of the handheld, the
value is always "BlackBerry."
Example The following code fragment displays the value of the appName property, which, in
the case of the handheld, will be BlackBerry:
document.write("The name of the client browser is " +
navigator.appName);

Tests whether or not data tainting is enabled.


Syntax navigator.taintEnabled()

Parameters none
Returns In the case of the BlackBerry Browser, this method always returns Boolean false.

140
C: JavaScript language reference

Example The following code fragment runs the function doThis if data tainting is enabled;
otherwise, it runs the function doThat:
if (navigator.taintEnabled()) {
doThis();
}
else doThat();

userAgent
Extracts the user agent from the user-agent header of the HTTP header. The user agent is used by
servers to identify the client browser. This property is read-only.
Syntax navigator.userAgent

Parameters none
Returns A string that represents the current user agent.
Example The following code fragment displays user agent information for the client browser:
document.write("The value of navigator.userAgent is " +
navigator.userAgent);

For example, in the case of a BlackBerry Browser client, this property might return
BlackBerry7210/4.0.0 (handheld model 7210, running version 4.0.0 of the
BlackBerry software).

141
BlackBerry Wireless Handheld Browser Content Developer Guide

Document
The Document object provides access to the elements in an HTML page from within your script. This includes the
properties of every form, link, and anchor (and, where applicable, any subelements), as well as global document
properties such as background and foreground colors.

Member type Member name Notes See Page


Properties alinkColor read-only 142
anchors Not supported. Returns an empty array. —
applets Not supported. Returns an empty array. —
bgColor read-only 143
classes Not supported. Returns an empty array. —
cookie read-write 144
domain read-only 144
embeds Not supported. Returns an empty array. —
fgColor read-only 145
formName read-only 145
forms read-only 146
height Treated as a contant. Returns the height of the device screen, in pixels. —
ids Not supported. Returns an empty array. —
images Not supported. Returns an empty array. —
lastModified read-only 146
linkColor read-only 147
plugins Not supported. Returns an empty array. —
referrer read-only 147
tags Not supported. Returns an empty array. —
title read-write 148
URL read-write 148
vlinkColor read-only 148
width Treated as a contant. Returns the width of the device screen, in pixels. —
Methods captureEvents() Not supported. —
close() — 143
contextual() Not supported. —
getSelection() Not supported. —
handleEvent() Not supported. —
open() — 147
releaseEvents() Not supported. —
routeEvents() Not supported. —
write() — 149
writeln() — 149

alinkColor
Provides the color that is used to identify active links in the document.

142
C: JavaScript language reference

This property is read-only.


Syntax document.alinkColor

Parameters none
Returns A string that represents the active link color. Colors can be represented as a string
literal (for example, "teal") or as a hexidecimal triplet (for example, "#0055FF").
Example The following code fragment returns the color that is used to identify active links in
the active document:
document.write("Active links in this document are represented
using the color " + document.alinkColor);

See also • bgColor


• fgColor
• linkcolor
• vlinkColor

bgColor
Returns the color that is used for the background of the active document.
This property is read-only.
Syntax document.bgColor

Parameters none
Returns A string that represents the background color of the document. Colors can be
represented as a string literal (for example, "teal") or as a hexidecimal triplet (for
example, "#0055FF").
Example The following code fragment returns the color that is used as the background color
in the active document:
document.write("The background color of this document is " +
document.bgColor);

See also • alinkColor


• fgColor
• linkcolor
• vlinkColor

close()
Closes a previously opened output stream.
Syntax document.close()

Parameters none

143
BlackBerry Wireless Handheld Browser Content Developer Guide

Example The following code fragment calls document.close() to close a stream that was
opened with document.open(). The document.close() method forces the
content of the stream to display in the window.
function doThis() {
var string1 = "Hi mom!";
var string2 = "Bye mom!";
document.open();
document.write(string1 + "<P>" + string2);
document.close();
}

See also • open()

cookie
Provides a report that details all visible and unexpired cookies that are associated with the specified
document.
This is a writable property.
Syntax document.cookie

Parameters none
Returns A comma-separated list that contains the cookies for the active document.
Examples The following code fragment displays information about visible and unexpired
cookies:
document.write("The following cookies are associated with this
document:
document.writeln(document.cookie)

The following code fragment creates 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=/";
}

domain
Provides the domain of the server that served the active document.
This property is read-only.
Syntax document.domain

144
C: JavaScript language reference

Parameters none
Returns A string that contains the domain name of the server that served the document.
Example The following code fragment returns the domain name of the hosting server:
document.write("This document originated from the " +
document.domain + "domain.");

fgColor
Returns the color that is used for the foreground (the text) of the active document. This property is
read-only.
Syntax document.fgColor

Parameters none
Returns A string that represents the foreground text color. Colors can be represented as a
string literal (for example, "teal") or as a hexidecimal triplet (for example,
"#0055FF").
Example The following code fragment returns the text color that is used in the active
document:
document.write("The text color of this document is " +
document.fgColor);

See also • alinkColor


• bgColor
• linkcolor
• vlinkColor

formName
Provides a specific form in the active document, referring to it by the name attribute of the HTML
<form> tag. This property is read-only.
Syntax document.formName

Parameters formName Represents the value of the name attribute for the HTML <form>
tag.
Returns The form associated with the given formName.
Example The following code fragment submits a form called loginForm:
document.loginForm.submit();

See also • forms

145
BlackBerry Wireless Handheld Browser Content Developer Guide

forms
Provides a list of all the form objects in the active document. This property is read-only.
Syntax document.forms[index]

Parameters index An integer or string that represents a form that is contained in the
array.
Returns An array that contains references to all the forms found in the active document.
Example The following code fragment submits the first form in the forms array:
document.forms[0].submit();

See also • formName

lastModified
Extracts the date that the document was last modified from the HTTP header. This property is read-
only.
Syntax document.lastModified

Parameters none
Returns A string representing the date that the document was last modified.
Example In the following code fragment, lastModified is used in a <SCRIPT> tag at the
end of an HTML file to display the modification date of the page:
document.write("This page updated on " +
document.lastModified);

146
C: JavaScript language reference

linkColor
Returns the color that is used by the active document to identify hyperlinks. This property is read-
only.
Syntax document.linkColor

Parameters none
Returns A string that represents the link color. Colors can be represented as a string literal
(for example, "teal") or as a hexidecimal triplet (for example, "#0055FF").
Example The following code fragment returns the color that is used as the link color in the
active document:
document.write("Hyperlinks in this document are represented
using the color " + document.linkColor);

See also • alinkColor


• bgColor
• fgColor
• vlinkColor

open()
Opens the output stream to the current document to collect data from the write() and writeln()
methods.
Syntax document.open()

Parameters none
Example The following code fragment calls document.close() to close a stream that was
opened with document.open(). The document.close() method forces the
content of the stream to display in the window.
function doThis() {
var string1 = "Hi mom!";
var string2 = "Bye mom!";
document.open();
document.write(string1 + "<P>" + string2);
document.close();
}

See also • close()

referrer
Provides the URL of the document through which the user arrived at the active document, if it
exists. This property is read-only.
Syntax document.referrer

Parameters none

147
BlackBerry Wireless Handheld Browser Content Developer Guide

Returns • If the user arrived at the active document from another document, a string that
contains the URL of the referring document is returned.
• If the user typed the URL or reached the active document through some other
means, an empty string is returned.
Example In the following code fragment, the getReferrer function is called from the active
destination document. It returns the URL of the source document:
function getReferrer() {
return document.referrer;
}

title
Retrieves or sets the title of the active document. This is a writable property.
Syntax document.title[="title"]

Parameters title The name of the document, as it appears in the title bar of the
BlackBerry Browser.
Returns A string that contains the title of the document, as specified by the <title>
element.
Example The following code fragment sets the title of the active document as "BlackBerry
Home Page":
document.title="BlackBerry Home Page";

URL
Retrieves or sets the complete URL of the active document. This property is read-only.
Syntax document.URL

Parameters none
Returns A string that contains the URL of the active document.
Example The following code fragment displays the URL of the current document:
document.write("The current URL is " + document.URL);

See also • window.location

vlinkColor
Returns the color that is used by the active document to identify links previously visited by the user.
This property is read-only.
Syntax document.linkColor

Parameters none

148
C: JavaScript language reference

Returns A string that represents the visited link color. Colors can be represented as a string
literal (for example, "teal") or as a hexidecimal triplet (for example, "#0055FF").
Example The following code fragment returns the color that is used as the link color in the
active document:
document.write("Visited links in this document are represented
using the color " + document.vlinkColor);

See also • alinkColor


• bgColor
• fgColor
• linkColor

write()
Writes HTML expressions to the specified document.
Syntax document.write(Expression1 [, Expression2, ...]);

Parameters Expression1 An HTML expression. Additional expressions can be included.


Example In the following code fragment, write() takes several arguments, including strings,
a numeric, and a variable, and displays the string "Hello world testing 123":
var mystery = "world";
msgWindow.document.write("Hello ", mystery, " testing ", 123);

In the following code fragment, write() takes two arguments to display the string
"Hello world...." The first argument is an assignment expression, and the
second argument is a string literal.
msgWindow.document.write(mystr = "Hello " + "world...");

In the following code fragment, the write method takes a single argument that is a
conditional expression. If the value of the variable age is less than 18, the method
displays "Minor." If the value of age is greater than or equal to 18, the method
displays "Adult."
msgWindow.document.write(status = (age >= 18) ? "Adult" :
"Minor");

See also • writeln()

writeln()
Writes HTML expressions to the specified document, and places a new line character at the end of
the expression.
Syntax document.writeln(Expression1 [, Expression2, ...]);

Parameters Expression1 An HTML expression. Additional expressions can be included.

149
BlackBerry Wireless Handheld Browser Content Developer Guide

Example The following code displays the type, description, and suffixes properties for
each supported MIME type on a client:
for (i=0; i < navigator.mimeTypes.length; i++) {
document.writeln("<TR VALIGN=TOP><TD>",i,
"<TD>",navigator.mimeTypes[i].type,
"<TD>",navigator.mimeTypes[i].description
"<TD>",navigator.mimeTypes[i].suffixes);
}

See also • write()

Form
The Form object enables you to access the elements of an HTML form that is used to collect information from
users.

Member type Member name Notes See Page


Properties action read-write 150
elements read-only 151
length read-only 152
method read-only 153
name read-only 153
target read-write 156
Methods handleEvent() This method is not supported. —
reset() — 155
submit() — 156
Event Handlers onClick — 153
onReset — 154
onSubmit — 154

action
Accesses the action attribute of an HTML <form> element, which defines the URL to which the
form is submitted. This is a writable property.
Syntax formName.action[="serverURL"]

Parameters formName The form for which data is being submitted. This parameter can be
either
• the value of the name attribute for the HTML <form> tag
• an element in the document.forms array
serverURL The URL of the server to which form field input information is sent.
This parameter can specify a CGI or LiveWire application on the server;
it can also be a mailto: URL if the form is to be mailed.

150
C: JavaScript language reference

Returns A string that describes the URL to which the submits data, unless serverURL is
specified.
Example The following code fragment specifies that responses to the loginForm form are
displayed in the msgWindow window:
document.loginForm.action="urlName";

See also • document.forms

elements
Provides a list of the elements that are found in the form. This property is read-only.
Syntax • formName.elements[index]
• formName.elements.length

Parameters formName The form that contains the listed elements. This parameter can be
either
• the value of the name attribute for the HTML <form> tag
• an element in the document.forms array
index An integer that represents an object of the form, or the name of the
element object as specified by its name attribute.
Properties length See "length" on page 141 for more information.
Returns An array that contains each element of the form.
Example The following code fragment writes a list of the elements contained in the form
loginForm:
document.write("This form contains the following HTML
elements:");
for (i=0; i < loginForm.elements.length; i++) {
document.write(loginForm.elements[i]);
}

See also • length


• document.forms

encoding
Specifies the value of the enctype attribute for the HTML <form> tag, which provides the MIME
encoding of the form. This property is read-only.
Syntax formName.encoding

151
BlackBerry Wireless Handheld Browser Content Developer Guide

Parameters formName The form for which the encoding type is being retrieved. This
parameter can be either
• the value of the name attribute for the HTML <form> tag
• an element in the document.forms array
Returns A string that indicates the MIME encoding of the form.
Example The following function returns the value of the loginForm encoding property:
function getEncoding() {
return document.loginForm.encoding;
}

See also • length


• document.forms

length
Specifies the number of elements in the form. This property is read-only.
Syntax • formName.length
• formName.elements.length

Parameters formName The form for which the number of elements is being retrieved. This
parameter can be either
• the value of the name attribute for the HTML <form> tag
• an element in the document.forms array
Returns An integer that represents the number of elements of the form.
Example The following code fragment writes a list of the elements contained in the form
loginForm:
document.write("This form contains the following HTML
elements:");
for (i=0; i < loginForm.length; i++) {
document.write(loginForm.elements[i]);
}

See also • elements


• document.forms

152
C: JavaScript language reference

method
Returns the value of the method attribute of the HTML <form> element, which defines the method
used to submit the form data to the server. This property is read-only.
Syntax formName.method

Parameters formName The form for which the submit method is being queried. This
parameter can be either
• the value of the name attribute for the HTML <form> tag
• an element in the document.forms array
Returns A string that represents the submit method. This string can have a value of either
GET or POST.

Example The following code fragment returns the submit method for the loginForm form:
document.write("This form submits data to the server using the
" + loginForm.method + " method");

See also • document.forms

name
Returns the value of the name attribute of the HTML <form> element, which provides the name of
specified form. This property is read-only.
Syntax formName.name

Parameters formName The form for which the value of the name attribute is being retrieved.
This parameter is an element in the document.forms array.
Returns An array that contains each element of the form.
Example The following code fragment writes a list of each of the forms found in the active
document:
document.write("This document contains the following HTML
forms:");
for (i=0; i < document.forms.length; i++) {
document.write(document.forms[i].name);
}

See also • document.forms

onClick
Specifies the event that follows when an object on click event occurs.
Syntax formName.onClick[="event"]

153
BlackBerry Wireless Handheld Browser Content Developer Guide

Parameters formName The name of the form. This parameter can be either
• the value of the name attribute for the HTML <form> tag
• an element in the document.forms array
event The event that is performed.
Returns A string describing the event which has been previously set to occur when a form
object is clicked, unless event is specified.
Example The following code fragment shows an onclick event handler that calls the
function isValidAddress() when the Calculate button is clicked.
<INPUT TYPE="button" VALUE="Calculate"
onClick="compute(this.form)">

See also • document.forms

onReset
Specifies the event that follows a reset action.
Syntax formName.onReset[="event"]

Parameters formName The name of the form. This parameter can be either
• the value of the name attribute for the HTML <form> tag
• an element in the document.forms array
event The event that is performed.
Returns A string describing the event which has been previously set to occur when the form
is reset, unless event is specified.
Example The following code fragment shows an onReset event handler that displays an alert
dialog informing the user that defaults have been reset.
<FORM NAME="form1" onSubmit="return isValidAddress()"
onReset="alert("Default values have been restored">
<B>Please enter your email address:</B>
<INPUT TYPE="text" NAME="address" SIZE=10><P>
<INPUT TYPE="submit" VALUE="Done" NAME="submit1">
<INPUT TYPE="reset" VALUE="Clear Form" NAME="Reset1">
</FORM>

See also • document.forms

onSubmit
Specifies the event that follows a submit action.
Syntax formName.onSubmit[="event"]

154
C: JavaScript language reference

Parameters formName The name of the form. This parameter can be either
• the value of the name attribute for the HTML <form> tag
• an element in the document.forms array
event The event that is performed.
Returns A string describing the event which has been previously set to occur when the form
is submitted, unless event is specified.
Example The following code fragment shows an onSubmit event handler that calls the
function isValidAddress(), which determines whether the email address entered
is valid before the form data is submitted to the server.
<FORM NAME="form1" onSubmit="return isValidAddress()"
onReset="alert("Default values have been restored">
<B>Please enter your email address:</B>
<INPUT TYPE="text" NAME="address" SIZE=10><P>
<INPUT TYPE="submit" VALUE="Done" NAME="submit1">
<INPUT TYPE="reset" VALUE="Clear Form" NAME="Reset1">
</FORM>

See also • document.forms

reset()
Clears user input and resets the default values of the form.
Syntax formName.reset()

Parameters formName The name of the form to be reset. This parameter can be either
• the value of the name attribute for the HTML <form> tag
• an element in the document.forms array
Example The following code fragment extracts data from the form located below. If the data
is not entered properly (for example, CA or AZ is not entered), the form is reset.
function isValidAddress(){
if (document.loginForm.address == .value == 'CA' ||
textObject.value == 'AZ') {
alert('Nice input');
}
else { document.loginForm.reset() }

Form document: loginForm


<FORM NAME="loginForm" onReset="alert('Please enter your .')">
Enter CA or AZ:
<INPUT TYPE="text" NAME="state" SIZE="2"
onChange=isValidAddress()<P>
</FORM>

See also • document.forms

155
BlackBerry Wireless Handheld Browser Content Developer Guide

submit()
Submits the specified form. This is equivalent to the user clicking a Submit button.
Syntax formName.submit()

Parameters formName The name of the form to be submitted. This parameter can be either
• the value of the name attribute for the HTML <form> tag
• an element in the document.forms array
Example The following code fragment submits a form called loginForm:
document.loginForm.submit();

If loginForm is the first form you create, you also can submit it as follows:
document.forms[0].submit();

See also • document.forms

target
Sets or returns the target window that responses are sent to after a form is submitted.
Note: Because the BlackBerry Browser is a single document interface (that is, it never displays more than one browser
window at a time) setting a target essentially has no effect.

This is a writable property.


Syntax formName.target[="windowName’]

Parameters formName The name of the form to be submitted. This parameter can be either
• the value of the name attribute for the HTML <form> tag
• an element in the document.forms array
windowName The name of the window to which responses are sent.
Returns A string that represents the name of the target window.
Example The following code fragment specifies that responses to the loginForm form are
displayed in the msgWindow window:
document.loginForm.target="msgWindow";

Screen
The Screen object returns information about the dimensions and color depth of the handheld display.

Members Name Notes See Page


Properties availHeight read-only 150
availLeft Treated as a contant. Returns 0. —
availTop Treated as a contant. Returns 0. —

156
C: JavaScript language reference

Members Name Notes See Page


availWidth read-only 151
colourDepth read-only 152
height read-only 153
pixelDepth read-only 153
width read-only 156

availHeight
Retrieves the height of the handheld screen. This property behaves identically to the height
property. This property is read-only.
Syntax screen.availHeight

Parameters none
Returns An integer that represents the screen height, in pixels.
Example The following code fragment returns the screen height:
document.write("The screen is " + screen.availHeight + " pixels
high.");

See also • availWidth


• height

availWidth
Retrieves the width of the handheld screen. This property behaves identically to the width property.
This property is read-only.
Syntax screen.availWidth

Parameters none
Returns An integer that represents the screen width, in pixels.
Example The following code fragment returns the screen width:
document.write("The screen is " + screen.availWidth + " pixels
wide.");

See also • availHeight


• width

colourDepth
Retrieves the bit depth of the color palette. This property behaves identically to the pixelDepth
property. This property is read-only.
Syntax screen.colourDepth

Parameters None

157
BlackBerry Wireless Handheld Browser Content Developer Guide

Returns • The bit depth of the hendheld color palette, if it uses one.
• If no palette is used, this property reflects the value of pixelDepth.
Example The following code fragment returns the bit depth of the color palette:
document.write("The handheld display has a pixel depth of " +
screen.colourDepth);

See also • pixelDepth

height
Retrieves the height of the screen height. This property behaves identically to the availHeight
property. This property is read-only.
Syntax screen.height

Parameters none
Returns An integer that represents the screen height, in pixels.
Example The following code fragment returns the screen height:
document.write("The screen is " + screen.height + " pixels
high.");

See also • availHeight

pixelDepth
Returns the bit depth of the palette. This property behaves identically to the colourDepth
property.This property is read-only.
Syntax screen.pixelDepth

Parameters none
Returns An integer that represents the color resolution, in bits per pixel, of the display.
Example The following code fragment returns the screen height:
document.write("The screen has a pixel depth of " +
screen.pixelDepth + " bits per pixel.");

See also • colourDepth

width
Retrieves the width of the screen. This property behaves identically to the availWidth property.
This property is read-only.
Syntax screen.width

Parameters none

158
C: JavaScript language reference

Returns An integer that represents the width of the screen, in pixels.


Example The following code fragment returns the screen width:
document.write("The screen is " + screen.width + " pixels
wide.");

See also • availWidth

159
BlackBerry Wireless Handheld Browser Content Developer Guide

Window
The Window object is created automatically when the browser encounters a <body> or <frame> tag, and returns
information about the window.

Members Name Notes See page


Properties blackberry read-only 162
closed Treated as a contant. Returns Boolean false. —
crypto Not supported. —
defaultStatus read-write 165
document read-only 165
frames read-only 166
history read-write 167
innerHeight Treated as a contant. Returns the screen height. —
innerWidth Treated as a contant. Returns the screen width. —
length read-only 168
location read-only 167
locationbar Not supported. —
menubar Not supported. —
name read-only 168
offscreenBuffering Treated as a contant. Returns Boolean false. —
opener read-write 169
outerHeight Treated as a contant. Returns the screen height. —
outerWidth Treated as a contant. Returns the screen width. —
pageXOffset Treated as a contant. Returns 0. —
pageYOffset Treated as a contant. Returns 0. —
parent read-write 169
personalbar Not supported. —
screenX Treated as a contant. Returns 0. —
screenY Treated as a contant. Returns 0. —
scrollbars Not supported. —
self read-write 170
status read-write 171
statusbar Not supported. —
toolbar Not supported. —
top read-write 172
window read-write 172
Methods alert() — 161
atob() — 162
back() — 162
blur() Stub implementation. This method has no effect. —
btoa() — 163

160
C: JavaScript language reference

Members Name Notes See page


captureEvents() Not supported. —
clearInterval() — 163
clearTimeout() — 163
close() — 164
confirm() — 165
disableExternalCapture() Not supported. —
enableExternalCapture() Not supported. —
find() Not supported. —
focus() Not supported. —
forward() — 166
handleEvent() Not supported. —
home() — 167
moveBy() Stub implementation. This method has no effect. —
moveTo() Stub implementation. This method has no effect. —
open() — 169
print() Stub implementation. This method has no effect. —
prompt() — 170
releaseEvents() Not supported. —
‘ resizeBy() Stub implementation. This method has no effect. —
resizeTo() Stub implementation. This method has no effect. —
routeEvent() Not supported. —
scroll() Stub implementation. This method has no effect. —
scrollBy() Stub implementation. This method has no effect. —
scrollTo() Stub implementation. This method has no effect. —
setHotKeys() Stub implementation. This method has no effect. —
setInterval() — 170
setTimeout() — 171
setZOptions() Stub implementation. This method has no effect. —
stop() — 172

alert()
Displays a standard alert dialog box with an OK button.
Syntax window.alert("message")

Parameters message A string, or a property of an existing object, that is displayed as the


dialog box message.
Example The following code fragment displays an alert dialog box informing users that they
did not enter information correctly.
window.alert("Please enter a name that is 8 characters or
less");

161
BlackBerry Wireless Handheld Browser Content Developer Guide

See also • confirm()


• prompt()

atob()
Decodes a given Base64 string.
Syntax window.atob(string)

Parameters string The string to be decoded.


Example The following code fragment decodes a variable named encodedURL into Base64
and assigns the result to the variable decodedURL:
var decodedURL=window.atob(encodedURL);

See also • btoa()

back()
Displays the previous URL in the history list.
Syntax window.back()

Parameters none
Example The following code fragment adds a custom button to an HTML page that displays
the previous item in the history list:
<P><INPUT TYPE="button" VALUE="< Back" onClick="window.back()">

See also • forward()


• home()

blackberry
Acts a pointer to the blackberry object. This property is read-only.
Syntax window.blackberry

Parameters none
Returns A pointer to the BlackBerry object.
Example The following code fragment displays the value of the network property:
document.write("The client BlackBerry handheld is communicating
on the " + window.blackberry.network + " wireless
network.");

See also • BlackBerry

162
C: JavaScript language reference

btoa()
Encodes a given string to Base64.
Syntax window.btoa(string)

Parameters string The string to be encoded.


Example The following code fragment encodes a URL into Base64 and assigns the result to
the variable encodeURL:
var encodeURL=window.btoa(URL)

See also • atob()

clearInterval()
Clears a repeating timer.
Syntax window.clearInterval(intervalID)

Parameters intervalID The ID (specified when the interval timer was created using
setInterval()) of the interval to be cleared.

Example After users clicks the Start button, the following code fragment writes the given
string every five seconds (5,000 milliseconds). The user must click the Stop button
to cancel the timer and stop new lines from being written.
<input type="button" value="Start"
onclick="timerID=setInterval(document.writeln("the
timer is on"), 5000);" />
<input type="button" value="Stop"
onclick="timerID=clearInterval(timerID);" />

See also • setInterval()

clearTimeout()
Clears a non-repeating timer.
Syntax window.clearTimeout(timeoutID)

Parameters timeoutID The identifier (set using setTimeout()) that specifies the timeout
evaluation that is cleared.

163
BlackBerry Wireless Handheld Browser Content Developer Guide

Example The following code fragment runs the displayAlert() function five seconds
(5,000 milliseconds) after the user clicks a button. If the user clicks the second
button before the message is displayed, the timeout is canceled and the message is
not displayed.
<INPUT TYPE="button" VALUE="5-second reminder"
NAME="remind_button"
onClick="timerID=setTimeout('displayAlert()',5000)"
>
<INPUT TYPE="button" VALUE="Clear the 5-second reminder"
NAME="remind_disable_button"
onClick="clearTimeout(timerID)">

See also • setTimeout()

close()
Closes the active window, going back one element in history.
Note: Because the BlackBerry Browser is a single document interface, there are no active or inactive windows; instead,
it stacks windows as successive items in the history list. If users close the current window, the previous document
appears. The only exception is when the current document is the first item in the history. In this case, closing the
window causes users to exit the browser.

Syntax window.close()

Parameters none
Example The following code fragment closes the active window and displays the previous
page in the history list:
window.close()

See also • open()


• opener

164
C: JavaScript language reference

confirm()
Displays a standard confirmation dialog box with an OK and Cancel button.
Syntax window.confirm("message")

Parameters message A string, or a property of an existing object, that is displayed as the


confirmation message.
Returns • If users click OK, the method returns true.
• If users click Cancel, the method returns false.
Example The following code fragment displays a confirmation dialog box asking users to
confirm that they want to submit a form:
window.confirm("Are you sure you want to submit this
information?")

See also • alert()


• prompt()

defaultStatus
Defines the default message that is displayed in the status bar. You can override this message using
the status property. This is a writable property.
Syntax window.defaultStatus = "message"

Parameters message The message that is displayed by default in the status bar.
Example The following code fragment sets the default status message:
window.defaultStatus = "Click the link to go to the BlackBerry
homepage.";

See also • status

document
Specifies the Document object that is contained within the window. This property is read-only
Syntax • window.document.propertyName
• window.document.methodName
Parameters propertyName The defaultStatus, status, length, or name property of the
Document object.

methodName Any method associated with the Document object.

165
BlackBerry Wireless Handheld Browser Content Developer Guide

Example In the following code fragment, the write() method takes several arguments,
including strings, a numeric, and a variable, and diplays the string "Hello world
testing 123":
var mystery = "world" msgWindow.document.write("Hello ",
mystery, " testing ", 123);

See also • Document

forward()
Goes forward one element in history.
Syntax window.forward()

Parameters none.
Example The following code adds a custom button to an HTML page that displays the next
item in the history list:
<P><INPUT TYPE="button" VALUE="< Back"
onClick="window.forward()">

See also • back()


• home()

frames
Specifies the frames that are contained by the current document. The handheld browser does not
support frames; instead, the browser displays a list of the frames in the frameset so that users can
open a selected frame as standalone page. This property is read-only.
Syntax window.frames[index]

Parameters index An integer that represents a child frame in the frameset, or the name of
the Frame object as specified by its name attribute.
Returns An array that contains the frame(s) associated with the document.
Example The following code fragment writes a list of the frames that are part of the current
document:
document.write("You have visited the following URLs during this
session:");
for (i=0; i < window.length; i++) {
document.write(window.frames[i]);
}

166
C: JavaScript language reference

history
Retrieves an array of recently accessed URLs, acquired from the History object. This property is
read-only.
Syntax • window.history[index]
• window.history.length
Parameters index An integer that represents a URL contained in the history list.
Properties length See "length" on page 141 for more information.
Returns An array that contains each element in the history list.
Example The following code fragment writes a list of the URLs that the user has visited
during the current session:
document.write("You have visited the following URLs during this
session:");
for (i=0; i < window.history.length; i++) {
document.write(window.history[i]);
}

See also • back()


• forward()

home()
Returns to the page configured by the user as the browser homepage.
Syntax window.home()

Parameters none
Example The following code fragment displays the homepage, as it is configured in the
browser settings:
<INPUT TYPE="button" VALUE="Go to your homepage"
onClick="window.parent.home()">

See also • back()


• forward()

location
Retrieves or sets the URL of the current window. This is a writable property.
Syntax • windowReference.location[.propertyName]
• windowReference.location.methodName(parameters)
Parameters windowReference The name of a window, or a synonym such as top or parent.

167
BlackBerry Wireless Handheld Browser Content Developer Guide

propertyName The defaultStatus, status, length, or name property of


the window object.
methodName Any method associated with the window object.
Returns A string containing the URL that is currently displayed in the specified window.
Example The following code fragment points the top window to the given URL:
top.location="http://www.blackberry.com/";

See also • document.URL

length
Returns the number of frames in a parent window. The handheld browser does not support frames;
instead, the browser displays a list of the frames in the frameset so that users can open a selected
frame as standalone page. This property is read-only.
Syntax windowReference.length

Parameters windowReference The name of a window, or a synonym such as top or parent.


Returns An array containing the frame(s) that are associated with the document.
Example The following code fragment writes a list of the frames that are part of the current
document:
document.write("You have visited the following URLs during this
session:");
for (i=0; i < window.length; i++) {
document.write(window.frames[i]);
}

name
Returns the name of the window. This property is read-only.
Syntax windowReference.name

Parameters windowReference The name of a window, or a synonym such as top or parent.


Returns none
Example In the following code fragment, the first statement creates a window called newWin.
The second statement displays "BlackBerry Home Page" in the alert dialog box,
because that is the value of the windowName argument of newWin.
newWin=window.open("http://www.blackberry.com","BlackBerry Home
Page");
alert(newWin.name);

168
C: JavaScript language reference

open()
Opens a new browser window.
Syntax [windowName]=[window.]open(URL)

Parameters windowName The name of the new window.


URL A string that represents the URL that is to be displayed in the child
window.
Example The following code fragment opens a new window that displays the BlackBerry web
site:
newWin=window.open("http://www.blackberry.com");

See also • close()


• opener

opener
A pointer back to the source window from the destination window. This is a writable property.
Syntax window.opener

Parameters none
Example The following code fragment closes the source window:
window.opener.close();

See also • close()


• open()

parent
A reference to the parent window. If no parent window exists, this property points to the current
active window. This is a writable property.
Syntax • parent.propertyName
• parent.methodName
Parameters propertyName The defaultStatus, status, length, or name property of the
Window object.

methodName Any method that is associated with the Window object.


Example The following code fragment closes the parent window when users click a button:
<INPUT TYPE="button" VALUE="Close the parent window"
onClick="window.parent.close()">

169
BlackBerry Wireless Handheld Browser Content Developer Guide

prompt()
Displays a prompt dialog box that prompts users for input.
Syntax window.prompt(message [,inputDefault])

Parameters message A string, or a property of an existing object, that is displayed as


the prompt message.
inputDefault Any string that represents the default value of the input field.
Example The following code fragment displays a dialog box that prompts users to specify the
number of donuts they want, and sets the default to12.
mainWindow.prompt("Enter the number of donuts you want to
order:", 12);

See also • alert()


• confirm()

self
A pointer to the current active window. This is a writable property.
Syntax • self.propertyName
• self.methodName

Parameters propertyName The defaultStatus, status, length, or name property of the


Window object.

methodName Any method that is associated with the Window object.


Example The following code fragment closes the current active window:
self.close();

See also • defaultStatus


• status
• length
• name
• window

setInterval()
Sets a timer that enables you to evaluate an expression at regular intervals.
Syntax intervalID=window.setInterval(expression, msec)

Parameters intervalID An identifier that is used only to cancel the timeout evaluation with
clearInterval().

expression The string expression or property of an existing object to be


evaluated.

170
C: JavaScript language reference

msec The time in milliseconds after which the expression is evaluated.


Example The following code fragment writes the given string every five seconds (5,000
milliseconds) after the user clicks the Start button. Users must click the Stop button
to cancel the timer and stop new lines from being written.
<input type="button" value="Start"
onclick="timerID=setInterval(document.writeln("the
timer is on"), 5000);" />
<input type="button" value="Stop"
onclick="timerID=clearInterval(timerID);" />

See also • clearInterval()

setTimeout()
Sets a non-repeating timer that enables you to evaluate an expression after a specified amount of
time.
Syntax timeoutID=window.setTimeout(expression, msec)

Parameters timeoutID An identifier that is used only to cancel the timeout evaluation with
clearTimeout().

expression The string expression or property of an existing object to be


evaluated.
msec The time in milliseconds after which the expression is evaluated.
Example The following code fragment writes the given string five seconds (5,000
milliseconds) after the user clicks a button. If the user clicks the second button
before the string is displayed, the timeout is canceled and the string is not written.
<INPUT TYPE="button" VALUE="Start"
onClick="timerID=setTimeout(document.writeln("five
seconds have passed")',5000)">
<INPUT TYPE="button" VALUE="Clear"
onClick="clearTimeout(timerID)">

See also • clearTimeout()

status
Defines the text in the status window. This is a writable property.
Syntax windowReference.status="message"

Parameters windowReference Any valid reference to the window object.


message The status message that is displayed.
See also • defaultStatus

171
BlackBerry Wireless Handheld Browser Content Developer Guide

stop()
Stops the current download.
Syntax window.stop()

Parameters none
Example The following code fragment adds a button that enables users to stop the current
download.
<input type=button value="STOP" onClick="stop();">

top
Refers to the top window. Access to window.top only provides a URL, not the Window object itself.
Because the BlackBerry Browser is a single document interface, it attempts to maintain some idea
of window relationships. In many cases, window.top points to the current window. However, if
users arrived at the current window from a frameset, window.top points to the parent frameset.
This is a writable property.
Syntax • top.propertyName
• top.methodName
Parameters propertyName The defaultStatus, status, length, or name property of the
Window object.

methodName Any method that is associated with the Window object.


Example The following code fragment sets the background color of a document called
myDocument to red.
top.myDocument.bgColor="red";

See also • defaultStatus


• length
• name
• self
• status

window
Refers to the current window. This is a writable property.
Syntax • window.propertyName
• window.methodName

Parameters propertyName The defaultStatus, status, length, or name property of the


Window object.

methodName Any method that is associated with the Window object.

172
C: JavaScript language reference

See also • defaultStatus


• length
• name
• self
• status

173
BlackBerry Wireless Handheld Browser Content Developer Guide

174
D
WMLScript language reference
Using WMLScript
WMLScript libraries

Using WMLScript
The Wireless Markup Language (WML) is a broad, fairly easy-to-use language that permits content developers to
create reasonable content that can be viewed on all WAP browsers. Unfortunately, it lacks many aspects of a true
scripting language.
The solution is WMLScript, a wireless scripting language that can co-exist with WML decks. It is similar to
JavaScript, and is a modified subset of ECMAScript.
WMLScripts are independent files called as external references within WML decks. They are compiled into
bytecode at runtime on the server before they are sent to the WAP browser. Like C, C++, and Java, the language is
case sensitive and has a construct that is similar to C.
The format of a WMLScript function is as follows:
extern function NAME( [PARAMETERS(S)] )
{
// body of function
}

The extern keyword makes the function public to external files. Do not include extern on functions that are only
called from within the script.
Parameter passing is fairly lax where type is not specified in the parameter list. The caller of the function is
responsible for making sure that parameters passed to a function are in the expected format and sequence.
Note: The handheld browser currently does not support floating-point values.

See “Scripting Basics” on page 197 for information on WMLScript reserved words and supported statements,
operators, and expressions.
BlackBerry Wireless Handheld Browser Content Developer Guide

WMLScript libraries
The strength of WMLScript is largely contained with the function libraries. The libraries include functions to deal
with numeric values, dialog boxes and alerts, strings, relative and absolute URLs, and the browser.
The following WMLScript libraries are supported.

Library Description See page


Lang The Lang library contains 15 core library functions. For example, you can perform operations on integers, 176
create random numbers, create absolute values, stop code that is currently running, and determine
support parameters.
Dialogs The Dialogs library contains three dialog box handlers that are used to display alert, confirmation, and 180
prompt dialog boxes. Users must respond to the displayed message or prompt in order for the SCRIPT to
continue running.
String The String library contains 14 functions that can be used to manipulate strings. 181
URL The URL library contains 14 functions that manipulate URLs. For example, you can extract the various 187
portions of the URL, escape and unescape special characters in the URL, determine the referring URL, and
so on.
Browser The Browser library contains seven functions that can be used to access the information that is 193
associated with the WML cards. For example, you can return to a previously viewed card, go to a new card,
refresh a card, and so on.

Lang
The Lang library contains 15 core library functions. For example, you can perform operations on integers, create
random numbers, create absolute values, stop code that is currently running, and determine support parameters.

Function Description See page


abort() Aborts the WMLScript and returns the passed string to the caller. 176
abs() Returns the absolute value of the passed number. 177
characterSet() Returns a value that identifies the supported character set. 177
exit() Exits the script and returns the passed message to the caller. 177
isInt() Tests whether the passed string can be converted into an integer value using parseInt(). 178
max() Determines the maximum value of two passed values in either integer or floating-point form. 178
maxInt() Returns the maximum value of an integer. 178
min() Returns the minimum value of two passed values in either integer or floating-point form. 178
minInt() Returns the minimum value of an integer. 179
parseInt() Converts a string into an integer value. 179
random() Returns a random number between 0 and the passed value. 179
seed() Initializes the random number generator. 180

abort()
Aborts the WMLScript and returns the passed string to the caller.
Syntax Lang.abort(ErrorMessage);

176
D: WMLScript language reference

Parameters ErrorMessage An error message that indicates the reason the script was aborted.
Returns No return value.
Example The following code fragment aborts the script and displays the given string:
Lang.abort("Script failure on line 123");

abs()
Returns the absolute value of the passed number.
Syntax Lang.abs(Number);

Parameters Number An integer or float value.


Returns The absolute value returned as an integer or float value.
Example The following code fragment returns positive “98765“:
var i_ret = Lang.abs(-98765);

The following code fragment returns positive “987.65“:


var f_ret = Lang.abs(-987.65);

characterSet()
Returns a value that identifies the supported character set.
Visit http://www.iana.org/assignments/character-sets for a current list of character sets.
Syntax Lang.characterSet();

Parameters None.
Returns The numeric character-set identifier.
Example The following code fragment returns “3“, representing US-ASCII:
var charset = Lang.characterSet();

exit()
Exits the script and returns the passed message to the caller.
Syntax Lang.exit(Message);

Parameters Message A message to pass back to the caller.


Returns No return value.
Example The following code fragment exits the script:
Lang.exit("Exit stage left");

177
BlackBerry Wireless Handheld Browser Content Developer Guide

isInt()
Tests whether the passed string can be converted into an integer value using parseInt().
Syntax Lang.isInt(StringValue);

Parameters StringValue A string representation of an integer value.


Returns • Boolean true if StringValue converts to integer form.
• Boolean false if StringValue cannot be converted.
Example The following code fragments return “true“:
isOkay1 = Lang.isInt("98765");
isOkay2 = Lang.isInt("-98765");
isOkay3 = Lang.isInt("9.8e2");

The following code fragment returns “false“:


isOkay4 = Lang.isInt("intni");

max()
Determines the maximum value of two passed values in either integer or floating-point form.
Syntax Lang.max(Value1, Value2);

Parameters Value1 The first of two integers or floating-point values to be compared.


Value2 The second of two integers or floating-point values to be compared.
Returns The highest value passed.
Example The following sample returns “13“:
var maxValue = Lang.max(12, 13);

maxInt()
Returns the maximum value of an integer.
Syntax Lang.maxInt();

Parameters None.
Returns The maximum integer value.
Example The following code fragment returns “2147483647“:
var theMax = Lang.maxInt();

min()
Returns the minimum value of two passed values in either integer or floating-point form.
Syntax Lang.min(Value1, Value2);

178
D: WMLScript language reference

Parameters Value1 The first of two integer or floating-point values to be compared.


Value2 The second of two integer or floating-point values to be compared.
Returns The smallest value passed.
Example The following code fragment returns “12“:
var theMin = Lang.min(12, 13);

minInt()
Returns the minimum value of an integer.
Syntax Lang.minInt();

Parameters None.
Returns The minimum integer value.
Example The following code fragment returns “-2147483648“:
var theMin = Lang.maxInt();

parseInt()
Converts a string into an integer value.
Syntax Lang.parseInt(StringInt);

Parameters StringInt Integer value in string form.


Returns Integer value.
Example The following code fragment returns “9876“:
var theInt1 = Lang.parseInt("9876");

The following code fragment stops parsing on the first error that it encounters, and
therefore returns “987“:
var theInt2 = Lang.parseInt("9876Hi!!");

random()
Returns a random number between 0 and the passed value.
Syntax Lang.random(MaxRange);

Parameters MaxRange Maximum integer value to draw from.


Returns A random integer within the specified range.
Example The following code fragment returns an arbitrary value between 0 and 9867:
var rndValue = Land.random(9867);

179
BlackBerry Wireless Handheld Browser Content Developer Guide

seed()
Initializes the random number generator.
Syntax Lang.seed(SeedValue);

Parameters SeedValue An integer seed value.


Returns An empty string.
Example The following code fragment initializes the random number generator with an initial
value of 98765:
var ret = Lang.seed(98765);

Dialogs
The Dialogs library contains three dialog box handlers that are used to display alert, confirmation, and prompt
dialog boxes. Users must respond to the displayed message or prompt for the script to continue running.

Function Description See


alert() Displays a standard alert dialog box with an OK button. 180
confirm() Displays a standard confirmation dialog box with an OK and Cancel button. 180
prompt() Displays a prompt dialog box that prompts users for input. 181

alert()
Displays a standard alert dialog box with an OK button.
Syntax Dialogs.alert(Message);

Parameters Message A string containing the message to display.


Returns An empty string.
Example The following code fragment displays a dialog box with the message “Wake up
now!”:
var ret = Dialogs.alert("Wake up now!");

confirm()
Displays a standard confirmation dialog box with an OK and Cancel button.
Syntax Dialogs.confirm(Message, Button1, Button2);

Parameters All parameters are strings or string literals.


Message The confirmation message.
Button1 The text of the first dialog box button.
Button2 The text of the second dialog box button.

180
D: WMLScript language reference

Returns • Boolean true if Button1 is selected by the user.


• Boolean false if Button2 is selected by the user.
Example The following example displays a dialog box with two buttons, Yes and No, and
contains the message “Exit?”:
var isOkay = Dialogs.confirm ("Exit?", "Yes", "No");

prompt()
Displays a prompt dialog box that prompts users for input.
Syntax Dialogs.prompt(Message, Default);

Parameters All parameters are string or string literals.


Message The confirmation message.
Default The default response.
Returns A string response.
Example The following code fragment displays a dialog box that asks users their age. The
default age is 30:
var Age = Dialogs.prompt("Your age", "30");

String
The String library contains 14 functions that can be used to manipulate strings.
The length of a string is determined by its total number of characters, including white space. Each character in the
string has an index position, where the first character is at position zero. A string can also be composed of a series
of elements that are delineated by separators. A separator can be any character.
The six types of white space are blank space, carriage return, form feed, line feed, horizontal tab, and vertical tab.

Function Description See page


charAt() Returns a single character that is located at the passed offset position within the passed string. 182
compare() Compares strings where ranking is performed based on the ASCII value of each character within the string. 182
elementAt() Locates a single element within the passed string buffer. 183
elements() Counts how many times a delimiter occurs within a passed buffer to determine the number of elements 183
in the buffer.
find() Searches for the first occurrence of the passed substring within the passed buffer. 183
format() Formats the passed numeric value as a string. 184
insertAt() Creates a new string from the passed buffer that includes the passed field and field delimiter, which is 185
inserted at the passed field element number.
isEmpty() Determines whether the passed string is empty. 185
length() Returns the length of a passed string. 185
removeAt() Removes a field from passed buffer at a specific element position. 186

181
BlackBerry Wireless Handheld Browser Content Developer Guide

Function Description See page


squeeze() Creates a string where all repeated white spaces in the passed string buffer are reduced to single spaces. 186
subString() Returns a portion of the passed string. 186
toString() Returns a string representation of the passed parameter. 186
trim() Eliminates any leading and trailing spaces from the passed string. 187

charAt()
Returns a single character that is located at the passed offset position within the passed string.
Syntax String.charAt(Buffer, Offset);

Parameters Buffer A buffer containing the source string.


Offset The offset position within the source buffer.
Returns A single character located at the offset position.
Example The following code fragment returns the character “c“:
var theChar1 = String.charAt("abcdef",3);

The following code fragment returns a null string:


var theChar2 = String.charAt("abcdef",8);

compare()
Compares strings where ranking is performed based on the ASCII value of each character within the
string.
Syntax String.compare(String1, String2);

Parameters String1 The first string to compare.


String2 The second string to compare.
Returns • 0 if the strings are identical.
• -1 if the first string is less than the second.
• 1 if the second string is less than the first.
Example The following code fragment returns “0“:
var theRes1 = String.compare("ABC", "ABC");

The following code fragment returns “1“:


var theRes2 = String.compare("abc", "ABC");

The following code fragment returns “-1“:


var theRes3 = String.compare("ABC", "abc");

182
D: WMLScript language reference

elementAt()
Locates a single element within the passed string buffer.
Syntax String.elementAt(Buffer, Element, Delimiter);

Parameters Buffer A string buffer that contains delimited fields.


Element A numeric value set to the desired field number. If the passed value
is less than 0, then the first field is assumed. If it is greater than
maximum number of elements, then the last field is assumed.
Delimiter The character(s) used to delimit fields.
Returns The requested field.
Example The following code fragment returns “'transformation“:
var Field = String.elementAt("In an extraordinary
transformation of heat to light, Gibbon rested.", 4, " ");

elements()
Counts how many times a delimiter occurs within a passed buffer to determine the number of
elements in the buffer.
Syntax String.elements(Buffer, Delimiter);

Parameters Buffer A string buffer that contains delimited fields.


Delimiter The character(s) used to delimit fields.
Returns The total count of Delimiter within Buffer.
Example The following code fragment returns “20“:
var howMany = String.elements("This descent from unity into
multiplicity recalled Constantine's timid policy of 'dividing
whatever is united', but its effects were far different", " ");

find()
Searches for the first occurrence of the passed substring within the passed buffer.
Syntax String.find(Buffer, SubString);

Parameters Buffer The source string buffer.


SubString The substring to search for within the passed buffer.
Returns: • Offset value of first occurrence of SubString (0-n).
• -1 if SubString is not found.
Example The following code fragment returns ”2“:
var theFirst = String.find( "Waterloo", "ter" );

183
BlackBerry Wireless Handheld Browser Content Developer Guide

format()
Formats the passed numeric value as a string.
Syntax String.format(FormatString, Value);

Parameters FormatString Specifies the format of the string, which is configured as follows:
%[width][.precision]type
• width: Optional. When set, it specifies the minimum number
of characters that must be returned in the string.
• .precision: Optional. When set, it specifies the required
decimal precision that is set based on the setting of type.
• type: Required. The type argument can have one of the
following values:
• d: The source is treated as a positive or negative integer
value in the form of [-]n, where n is one or more decimal
digits.
If .precision is set, then the output value is padded on the
left side with up to the .precision number of zeroes.
• f: The source is treated as a positive or negative floating
point value in the form of [-]n.n, where n is one or more
decimal digits.
If .precision is set, then it is used to set the number of
digits after the decimal point, with at least one digit
appearing before the decimal point. The default precision
is 6. If 0 or a null value is specified after the decimal point,
then the decimal component is truncated.
• s: The source is treated as a string.
In this case, the width argument can be used to set the
minimum string size, and the .precision argument can
be used to set the maximum string size.
Value The value to be formatted as a string.
Returns A formatted string.
Example The following code fragment returns “BlackBerry rules!“:
var s5 = String.format("BlackBerry %s", "rules!");

The following code fragment returns “ 98.765%“ (with eight preceding blank
spaces):
var s6 = String.format("%10.3F%%", 98.7654);

184
D: WMLScript language reference

insertAt()
Creates a new string from the passed buffer that includes the passed field and field delimiter, which
is inserted at the passed field element number.
Syntax String.insertAt(Buffer, Field, Element, Delimiter);

Parameters Buffer A string buffer that contains delimited fields.


Field The string field to insert.
Element A numeric element (0-n) where Field is to be inserted. If the
passed value is less than 0, then is 0 is used. If it is greater than
maximum number of elements, then Field is appended to the end
of buffer.
Delimiter The delimiter character to be inserted after Field.
Returns The resulting string.
Example The following code fragment returns “1|99|2|“:
var nStr = String.insertAt("1|2|","99",1,"|");

isEmpty()
Determines whether the passed string is empty.
Syntax String.isEmpty(Buffer);

Parameters Buffer The source string buffer.


Returns • Boolean true if the string is empty.
• Boolean false if it is not empty.
Example The following code fragment returns true:
var NULLString = "";
var IsNULL = String.isEmpty(NULLString);

length()
Returns the length of a passed string.
Syntax String.length(Buffer);

Parameters Buffer The source string buffer.


Returns The string length (0-n).
Example The following code fragment returns 6:
var theLength = String.length("yellow");

The following code fragment returns 0:


var theLength = String.length("");

185
BlackBerry Wireless Handheld Browser Content Developer Guide

removeAt()
Removes a field from the passed buffer at a specific element position.
Syntax String.removeAt(Buffer, Element, Delimiter);

Parameters Buffer The source string buffer.


Element The field element to remove from the buffer.
Delimiter The character delimiter used to separate fields.
Returns Buffer, without the requested element.

Example The following code fragment returns “1|3|“:


var Res = String.removeAt("1|2|3|",1,"|");

squeeze()
Creates a string where all repeat white spaces in the passed string buffer are reduced to single
spaces.
Syntax String.squeeze(Buffer);

Parameters Buffer The source string buffer.


Returns Buffer with “squeezed” spaces.

Example The following code fragment returns “My BlackBerry is cool!“:


var SqzMe = String.squeeze("MygrgBlackBerrygrgisgrgcool!");

subString()
Returns a portion of the passed string.
Syntax String.subString(Buffer, Start, Size);

Parameters Buffer The source string buffer.


Start The position of the first character of the substring in the source (0-n).
Size The total number of characters to extract.
Returns The requested substring.
Example The following code fragment returns “Berry“:
var SS = String.subString(“BlackBerry", 5, 5);

toString()
Returns a string representation of the passed parameter.
Syntax String.toString(Value);

186
D: WMLScript language reference

Parameters Value Any value.


Returns A string.
Example The following code fragment returns a string with the value “98.76”:
var theString = String.toString(98.76);

trim()
Eliminates any leading and trailing spaces from the passed string.
Syntax String.trim(Buffer);

Parameters Buffer The source string buffer.


Returns The string buffer without leading and trailing spaces.
Example The following code fragment returns “My BlackBerry is cool!“:
var isTrimmed = String.trim(" My BlackBerry is cool! ");

URL
The URL library contains 14 functions that manipulate URLs. For example, you can extract the various portions of
the URL, escape and unescape special characters in the URL, determine the referring URL, and so on.
A URL is composed of some or all of the following components:
scheme://host:port/path;parameters$query#fragment.

Function Description See page


escapeString() Returns a string where special characters are changed into hexadecimal escape sequences. 187
getBase() Returns the absolute URL (without the fragment) of the current WMLScript. 188
getFragment() Returns the fragment portion of the passed URL. 188
getHost() Returns the host that is specified within the passed URL. 189
getParameters() Returns the parameters within the last path segment of the passed URL. 189
getPath() Returns the path that is specified within the passed URL. 189
getPort() Returns the port specified within the passed URL. 190
getQuery() Returns the query portion of the passed URL. 190
getReferer() Returns the smallest relative URL for the page, deck, or script that called the current script. 190
getScheme() Returns the scheme within the passed URL. 191
isValid() Validates the syntax of the passed URL. 191
loadString() Returns the content referred by the passed absolute URL and content type. 191
resolve() Combines the passed base and relative URLs to return an absolute URL. 192
unescapeString() Returns a string where escaped characters have been restored to original form. 192

escapeString()
Returns a string where special characters are changed into hexadecimal escape sequences.

187
BlackBerry Wireless Handheld Browser Content Developer Guide

The following special characters should be converted:


• reserved characters: semicolon (;), slash (/), question mark (?), colon (:), at symbol (@),
ampersand (&), equal sign (=), plus sign (+), and dollar sign ($)
• unwise characters: left and right brace ( { } ), verical slash (|), backslash (\), caret (^), left and
right brackets ( [ ] ), and apostrophe (‘)
• delimiters: greater than sign(<), less than sign (>), number sign (#), percent symbol (%), and
quotation marks (“)
The resulting escaped characters are as follows:
• control characters (ASCII %00 to %1F and %7F)
• space (ASCII %20)
• upper range (ASCII %8F to %FF)
Syntax URL.escapeString(URL);

Parameters URL A string buffer containing the unescaped URL.


Returns A string buffer containing the escaped URL.
Example The following code fragment returns “http%3a%2f%2frim.com%2f”:
URL.escapeString("http://rim.com/");

getBase()
Returns the absolute URL (without the fragment) of the current WMLScript.
Syntax URL.getBase();

Parameters None.
Returns The absolute URL.
Example The following code fragment returns ”http://rim.com/script.wmls”:
var theURL = "http://rim.com/script.wmls#frag"
var absURL = URL.getBase();

getFragment()
Returns the fragment portion of the passed URL.
Syntax URL.getFragment(URL);

Parameters URL The passed URL.


Returns The URL fragment.
Example The following code fragment returns “frag“:
var theURL = "http://rim.com/script.wmls#frag"
var theFrag = URL.getFragment(theURL);

188
D: WMLScript language reference

getHost()
Returns the host that is specified within the passed URL.
Syntax URL.getHost(URL);

Parameters URL The passed URL.


Returns The host component of the URL.
Example The following code fragment returns “www.rim.com”:
var theURL = "http://www.rim.com/script.wmls";
var theHost = URL.getHost(theURL);

The following code fragment returns a null string, as the passed URL contains no
host component:
var theURL = "script.wmls";
var theHost = URL.getHost(theURL);

getParameters()
Returns the parameters within the last path segment of the passed URL.
Syntax URL.getParameters(URL);

Parameters URL The passed URL.


Returns The parameters of the URL.
Example The following code fragment returns “param1;param2”:
var theURL = "http://rim.com/sample.php;param1;param2";
var parms = URL.getParameters(theURL);

The following code fragment returns a null string, as the passed URL contains no
parameters:
var theURL = "http://www.rim.com/script.wmls";
var parms = URL.getParameters(theURL);

getPath()
Returns the path that is specified within the passed URL.
Syntax URL.getPath(URL);

Parameters URL The passed URL.


Returns The path component.

189
BlackBerry Wireless Handheld Browser Content Developer Guide

Example The following code fragment returns “test/sample.php“:


var theURL = "http://rim.com/test/sample.php";
var thePath = URL.getPath(theURL);

The following code fragment returns a null string, as the passed URL contains no
path:
theURL = "http://rim.com/";
thePath = URL.getPath(theURL);

getPort()
Returns the port that is specified within the passed URL.
Syntax URL.getPort(URL);

Parameters URL The passed URL.


Returns The port component.
Example The following code fragment returns “80”:
var theURL = "http://www.rim.com:80";
var thePort = URL.getPort(theURL);

The following code fragment returns, a null string, as the passed URL contains no
port:
theURL = "http://www.rim.com";
thePort = URL.getPort(theURL);

getQuery()
Returns the query portion of the passed URL.
Syntax URL.Query(URL);

Parameters URL The passed URL.


Returns The query portion of the URL.
Example The following code fragment returns “4884”:
var theURL = "http://rim.com/sample.php?id=4884";
var theQuery = URL.getQuery(theURL);

The following code fragment returns a null string, as the passed URL contains no
query component:
theQuery = URL.getQuery("http://www.rim.com");

getReferer()
Returns the smallest relative URL for the page, deck, or script that called the current script.
Syntax URL.getReferer();

190
D: WMLScript language reference

Parameters None.
Returns The referring URL.
Example The following code fragment might return the full URL or something relative such as
“mydeck.wml”. If there is no referrer, it returns a null string:
var whoCalled = URL.getReferer();

getScheme()
Returns the scheme within the passed URL.
Syntax URL.getScheme(URL);

Parameters URL The passed URL.


Returns The scheme of the URL.
Example The following code fragment returns “http”:
var theURL = "http://www.rim.com/";
var theScheme = URL.getScheme(theURL);

The following code fragment returns a null string, as the passed URL contains no
scheme component:
var theURL = "www.rim.com/";
var theScheme = URL.getScheme(theURL);

isValid()
Validates the syntax of the passed URL.
Syntax URL.isValid(URL);

Parameters URL The passed URL.


Returns • Boolean true if the syntax is correct.
• Boolean false if the syntax is not correct.
Example The following code fragment returns “true”:
var theURL = "http://www.rim.com/";
var isOkay = URL.isValid(theURL);

The following code fragment returns “false”:


var theURL = "http:/www.rim.com/";
var isOkay = URL.isValid(theURL);

loadString()
Returns the content referred by the passed absolute URL and content type.
Syntax URL.loadString(URL, ContentType);

191
BlackBerry Wireless Handheld Browser Content Developer Guide

Parameters URL A string that contains an absolute URL.


ContentType A string that contains the accepted content type that must be
prefixed with “text/”.
Returns A string buffer that contains the requested page, deck, or script.
Example The following code fragment returns the page contents:
var theURL = "http://www.rim.com/index.shtml";
var theCT = "text/plain" );
var theContent = URL.loadString(theURL, theCT);

resolve()
Combines the passed base and relative URLs to return an absolute URL.
Syntax URL.resolve(baseURL, relURL);

Parameters baseURL The base portion of the passed URL (for example,
“http://www.rim.com/”).
relURL The relative path to a page, deck, or script (for example,
“index.shtml”).
Returns The resulting absolute URL.
Example The following code fragment returns “http://www.rim.com/index.shtml”:
var baseURL = "http://www.rim.com/";
var relURL = "index.shtml" );
var absURL = URL.resolve(baseURL, relURL);

unescapeString()
Returns a string where escaped characters have been restored to original form.
Syntax URL.unescapeString(escURL);

Parameters escURL An escaped URL.


Returns An unescaped URL.
Example The following code fragment returns “http://rim.com/”:
var escURL = "http%3a%2f%2frim.com%2f";
var newURL = URL.unescapeString(escURL);

192
D: WMLScript language reference

Browser
The Browser library contains seven functions that can be used to access the information that is associated with
the WML cards. For example, you can return to a previously viewed card, go to a new card, refresh a card, and so
on.

Function Description See page


getCurrentCard() Returns the smallest relative URL of the current card being processed by the browser. If the current 193
card has a different base than the current script, this function returns the absolute URL of the card.
getVar() Returns the value of the passed variable name within the current browser context. 193
go() Navigates the browser to the given URL. 193
newContext() Resets the browser context and clears all variables. 194
prev() Navigates the browser to the previous card. 194
refresh() Refreshes the current page by pulling it from the server. 194
setVar() Sets the value of a variable. 194

getCurrentCard()
Returns the smallest relative URL of the current card being processed by the browser. If the current
card has a different base than the current script, this function returns the absolute URL of the card.
Syntax Browser.getCurrentCard();

Parameters None.
Returns A relative or absolute URL.
Example The following code fragment returns the current card being processed by the
browser:
var relURL = Browser.getCurrentCard();

getVar()
Returns the value of the passed variable name within the current browser context.
Syntax Browser.getVar(strName);

Parameters strName The name of the variable for which the value is to be returned.
Returns String value or invalid if not found.
Example The following code fragment returns the variable name (for example, “revers”):
var varVal = Browser.getVar("userid");

go()
Navigates the browser to the given URL.
Syntax Browser.go(navURL);

Parameters navURL A relative or absolute URL to which the browser is pointed.

193
BlackBerry Wireless Handheld Browser Content Developer Guide

Returns An empty string.


Example The following code fragment navigates the browser to a relative URL:
var ret = Browser.go("newpage.wml");

The following code fragment navigates the browser to an absolute URL:


var ret = Browser.go("http://www.xyzzy.com/");

newContext()
Resets the browser context and clears all variables.
Syntax Browser.newContext();

Parameters None.
Returns An empty string.
Example The following code fragment resets the browser context:
var ret = Browser.newContext();

prev()
Navigates the browser to the previous card.
Syntax Browser.prev();

Parameters None.
Returns An empty string.
Example The following code fragment navigates the browser to the previous card:
var ret = Browser.prev();

refresh()
Refreshes the current page by pulling it from the server.
Syntax Browser.refresh();

Parameters None.
Returns An empty string.
Example The following code fragment refreshes the current page:
var ret = Browser.refresh();

setVar()
Sets the value of a variable.
Syntax Browser.setVar(varName, varValue);

194
D: WMLScript language reference

Parameters varName The name of the variable for which the value is to be set.
varValue The value to assign to varName.
Returns • Boolean true on success.
• Boolean false on failure.
Example The following code fragment sets the variable password to a value of “xyzzy”:
var isSet = Browser.setVar("password", "xyzzy");

195
BlackBerry Wireless Handheld Browser Content Developer Guide

196
E
Scripting Basics
Reserved words
Statements
Operators and expressions

Reserved words
The following are reserved words in WMLScript and/or JavaScript and cannot be used to name functions,
variables, methods, or objects.
• abstract • else • instanceof • struct
• access • equiv • int • super
• agent • enum • interface • switch
• Boolean • export • isvalid • synchronized
• break • extends • long • this
• byte • extern • meta • throw
• case • false • name • throws
• catch • final • native • transient
• char • finally • new • true
• class • float • null • try
• const • for • package • typeof
• continue • function • path • url
• debugger • goto • private • use
• default • header • protected • user
• delete • http • public • var
• div • if • return • void
• do • implements • short • volatile
• domain • import • sizeof • while
• double • in • static • with
BlackBerry Wireless Handheld Browser Content Developer Guide

Statements
The following WMLScript and/or JavaScript statements are supported by the handheld.

Statement Description Example Supported by


WMLScript JavaScript
break Stops a for or while loop statement. All processing is var i = 0; a a
immediately stopped inside the loop and the loop is while ( i < 6 ) {
if ( i == 3 ) {
exited. The program continues with the first line of code break;
(if any) after the terminated loop. i++;
}
Using a break statement outside of a for or while
return i*x;
loop statement generates an error. }
continue Stops a block of statements inside a for or while loop i = 0; a a
statement and redirects the program to another block of n = 0;
while ( i < 5 ) {
statements inside the loop. i++;
In a for loop, the program jumps to the for counting if ( i == 3 )
continue;
variable test expression.
n += i;
In a while loop, the program jumps to the while }
condition test.
do ... Runs one or more statements at least once, checking that var i = 0; a
while a certain condition is met each time before repeating. If do {
document.write( i + ".<BR>");
that condition is not met, then control moves to the i+=2;
statement immediately after the loop. }
while( i<20 );
for Repeats a block of statements as long as a stated test for( i=0; i<10; i++) a a
condition, based upon a counting mechanism, remains document.write( i + ".<BR>");
true.
for ... Iterates a declared variable over every property in a var i; a
in specified object. for( i in mimeArray )
document.write( i + "<BR>");
if ... Evaluates a specified expression contained in the if if( calcaverage (x,y,z ) < 10 ) a a
else statement to determine if it is true or false. If true, a document.write("The average is
less than 10.");
block of statements associated in the if statement is else
run. If false, the if statement is immediately exited, document.write("The average is
unless an optional else clause exists. 10 or more.");
Use the optional else clause to run a block of
statements if the specified condition is false. Note that
you cannot provide a test expression for the else
statement.
return Specifies the value to be returned by a function and function square( x ) { a a
performs the act of returning that value to where the return x * x;
}
function was called from.

198
E: Scripting Basics

Statement Description Example Supported by


WMLScript JavaScript
switch Tests an expression against a number of case options , switch (modelNumber ) { a
then runs the statements associated with the first case case "6700" :
document.write ("monochrome");
that matches the expression. If no match is found, the break;
program looks for a set of default statements to run, and case "7700" :
if these aren't found, it carries on with the statement document.write ("color");
immediately following switch. break;
default :
document.write ("Sorry, " + i +
" is not a valid
model.<BR>");
}
var Declares a variable. Outside a function it is optional. var i = 0; a a
While a variable can be declared by assigning it a value, var num_hits = 0, cust_no = 0;
there are two cases in functions where using var is
necessary:
• If a global variable of the same name exists.
• If recursive or multiple functions use variables of the
same name.
You can also declare more than one variable and,
optionally, assign values at the same time.
while Repeats a block of statements as long as a stated test var i = 0; a a
condition, based upon an evaluated expression, remains while( i<11 ) {
document.write (i + <BR>");
true. i++;
}
with A statement that establishes the default object for a set with(displayType) { a a
of statements. Within the set of statements, any property if( model < 7000 )
document.write("monochrome");
references that do not specify an object are assumed to else
be for the default object. document.write("color");
}

199
BlackBerry Wireless Handheld Browser Content Developer Guide

Operators and expressions


The following WMLScript and/or JavaScript operators and expressions are supported by the handheld.

Operator Symbol Description Example Supported by


type WMLScript JavaScript
Arithmetic + Addition. Returns the sum of two numerical if x = 5 and y = 2 a a
values. then x + y returns 7
- Subtraction. Subtracts one numerical value from if x = 5 and y = 2 a a
another. then x - y returns 3
* Multiplication. Returns the product of two if x = 5 and y = 2 a a
numerical values. then x * y returns 10
/ Division. Divides one numerical value by another. if x = 5 and y = 2 a a
then x / y returns 2.5
div Integer division. Divides one numerical value by if x = 5 and y = 2 a
another, and rounds the result down to the then x div y returns 2
nearest whole number.
% Remainder. Returns the integer remaining when if x = 5 and y = 2 a a
one operand is divided by another. then x % y returns 1
Unary + Positive. Precedes an operand to indicate it is if x = 5 a a
greater than zero. then +x returns 5
- Negation. Precedes an operand and negates it. if x = 5 a a
then -x returns -5
++ Increment. When positioned if x= 5: a a
• after the operand, it returns the value before • y = x++ sets y to 5, then increases x
incrementing to 6
• before the operand, it increments before • y = ++x increases x to 6, then sets y
returning the value. to 6
-- Decrement. When positioned if x= 5: a a
• after the operand, it returns the value before • y = x++ sets y to 5, then decreases x
decrementing to 4
• before the operand, it decrements before • y = ++x decreases x to 4, then sets y
returning the value. to 4
~ Bitwise NOT. Flips the bit values of its operand. ~ 9 returns 6 (1001 becomes 110) a a

200
E: Scripting Basics

Operator Symbol Description Example Supported by


type WMLScript JavaScript
Comparison == Equal. Returns true if the values of the left and if x = 5 and y = 2 a a
right operands are identical. then x == y returns false
> Greater than. Returns true if the value of the left if x = 5 and y = 2 a a
operand is higher than the value of the right then x > y returns true
operand.
< Less than. Returns true if the value of the left if x = 5 and y = 2 a a
operand is lower than the value of the right then x < y returns false
operand.
>= Greater than or equal. Returns true if the value of if x = 5 and y = 2 a a
the left operand is equal to or greater than the then x >= y returns true
value of the right operand.
<= Less than or equal. Returns true if the value of the if x = 5 and y = 2 a a
left operand is equal to or less than the value of then x <= y returns false
the right operand.
!= Not equal. Returns true if the values of the left if x = 5 and y = 2 a a
and right operands are not equal. then x != returns true
Bitwise << Left shift. Shifts the digits of the binary 9 << 2 returns 36 a a
representation of the first operand to the left by (1001 becomes 100100)
the number of places specified by the second
operand. The spaces that are created to the right
are filled in by zeros, and any digits falling off the
left are discarded.
>> Sign-propagating right shift. Shifts the digits of 9 >> 2 returns 2 a a
the binary representation of the first operand to (1001 becomes 10)
the right by the number of places specified by the -9 >> 2 returns -3, because the sign is
second operand, discarding any numbers shifted preserved
off to the right. Copies of the left most bit are
shifted in from the left.
>>> Right shift with zero fill. Shifts the digits of the 19 >>> 2 returns 4 a a
binary representation of the first operand to the (10011 becomes 100)
right by the number of places specified by the
second operand, discarding any digits shifted off
to the right and adding zeros to the left.
& AND. Returns "1" for each bit position where the 15 & 9 would return 9 a a
corresponding bits of its operands is "1". (1111 & 1001 = 1001)
| OR. Returns "1" for each bit position where one 15 | 9 would return 15 a a
or both of the corresponding bits of its operands (1111 | 1001 = 1111)
is "1".
^ Exclusive OR. Returns "1" for each bit position 15 ^ 9 would return 6 a a
where only one (not both) of the corresponding (1111 ^ 1001 = 110)
operands is "1".

201
BlackBerry Wireless Handheld Browser Content Developer Guide

Operator Symbol Description Example Supported by


type WMLScript JavaScript
Assignment = Assignment. Assigns a literal or numerical value x = y (sets the value of x to the value of y) a a
on the right to the variable on the left.
+= Addition and assignment. Adds the operand to if x = 5 and y = 2 a a
the variable and sets the variable to the result. then x += y returns 7
(equivalent to x = x + y)
-= Subtraction and assignment. Subtracts the if x = 5 and y = 2 a a
operand from the variable and sets the variable to then x -= y returns 3
the result. (equivalent to x = x - y)
*= Multiplication and assignment. Multiplies the if x = 5 and y = 2, a a
variable and the operand and sets the variable to then x *= y returns 10
the result. (equivalent to x = x * y)
/= Division and assignment. Divides the variable by if x = 5 and y = 2, a a
the operand and sets the variable to the result. then x /= y returns 2.5
(equivalent to x = x / y)
div= Integer division and assignment. Divides the if x = 5 and y = 2, a
variable by the operand, rounds the result down then x div= y returns 2
to the nearest whole number, and sets the (equivalent to x = x div y)
variable to the result.
%= Remainder and assignment. Determines the if x = 5 and y = 2, a a
integer remainder when the variable is divided by then x %= y returns 1
the operand, and sets the variable to the (equivalent to x = x % y)
remainder value.
<<= Bitwise left shift and assignment. Shifts the digits if x = 9 and y = 2, a a
of the bitwise variable left by the number of then x <<= y returns 36
positions specified by the operand, and sets the (equivalent to x = x << y)
variable to the result. This operation is not
permissible if the initial value of the variable is
negative.
>>= Bitwise right shift and assignment. Shifts the if x = 9 and y = 2, a a
digits of the bitwise variable right by the number then x >>= y returns 2
of positions specified by the operand, and sets the (equivalent to x = x >> y)
variable to the result. This operation is not
permissible if the initial value of the variable is
negative.
>>>= Bitwise right shift zero fill and assignment. Shifts if x = 19 and y = 2, a a
the digits of the bitwise variable right by the then x >>>= y returns 4
number of spaces specified by the operand, and (equivalent to x = x >>> y)
sets the value of the variable to the result.
&= Bitwise AND and assignment. Performs a bitwise if x = 15 and y = 9, a a
AND operation on the variable and the operand, then x &= y returns 9
and sets the value of the variable to the result. (equivalent to x = x & y)
|= Bitwise OR and assignment. Performs a bitwise if x = 15 and y = 9, a a
OR operation on the variable and the operand, then x |= y returns 15
and sets the value of the variable to the result. (equivalent to x = x | y)
^= Bitwise exclusive OR and assignment. Performs a if x = 15 and y = 9, a a
bitwise exclusive OR operation on the variable then x ^= y returns 6
and the operand, and sets the value of the (equivalent to x = x ^ y)
variable to the result.
202
E: Scripting Basics

Operator Symbol Description Example Supported by


type WMLScript JavaScript
Logical && AND. Returns a Boolean true if both of the given if x = 5 and y = 2 a a
expressions are true. then (y < x) && (y > (x >>2)) returns true
|| OR. Returns a Boolean true if one of the given if x = 5 and y = 2 a a
expressions are true. then (x < y) || (y> (x >> 2)) returns true
! NOT. Returns Boolean true if the given expression if x = 5 and y = 2 a a
is false, and returns Boolean false if the given then ! (x < y) returns true, and (y < x )
expression is true. returns false
String + Concatenate. Joins two string values together. "new" + "_string" returns a a
"new_string"
+= Concatenate and assignment. Adds a string to the If mystring = "new" then a a
string variable and sets the variable to the result. mystring += "_string" returns
"new_string"
Special ?: Conditional operator that takes three operands var IsOkay = ( Value == "Food" a a
and is used to replace simple if statements. The ) ? 1 : 0;
first operand is a condition that evaluates to true
or false, the second is to be returned on true, and
third to be returned on false.
, Comma. Used to include multiple expressions for (el = 0, id = 100; a a
where only one is required, such as in a for loop. el < 10; el++, id+=10)
It evaluates both its operands and returns the
value of the second.
typeof Returns the data type of the given variable as one var result = typeof data; a a
of number, string, Boolean, object, or function.
isvalid Tests whether an expression is valid. It returns var IsOk_1 = isvalid (99/0); a
true if the passed expression is valid, or else it
returns false.
new Creates an instance of a user-defined object type formsArray = new array (form1, a
or of one of the following built-in object types: form2, form3)
array, Boolean, date, function, math, number, or
string. Uses the following syntax:
objectName = new objectType
( param1 [,param2] ...[,paramN] )
delete Deletes an object, an object property, or a x=42 a
specified element in an array, returning true if the delete x
operation is possible, and false if it is not.
void Specifies an expression to be evaluated without void (document.form. a
returning a value. submit())

203
BlackBerry Wireless Handheld Browser Content Developer Guide

204
Index

Index
A troubleshooting push applications, 94
accept header, 34 bookmarks
access control, WML, 54 about, 24
actions, WML, 54, 57 browser
application pushes and downloads, supported, 16 acceptable content, 34, 35, 53
attributes browser detection, 34, 35
HTML, 39, 43, 44 creating effective images, 29
WML, 54, 56, 57, 58, 59 design guidelines, 27, 29, 46, 60
HTML and XHTML support, 97
B links, 27
BlackBerry menus, 55
model number, 34 push applications, 67
simulator, 47, 60, 65, 66 script support, 40, 53
BlackBerry Browser about, 9 supported content, 35
BlackBerry Browser configuration, 9 WML support, 129, 175
about, 11 browser push
options, 25 about, 67
BlackBerry Browser content
mobile media, 15 C
multi-part content, 17 cache, 24
supported markup languages, 15 cards, WML, 53, 55, 56
supported scripts, 16 central push server, 71
BlackBerry Browser features check boxes
bookmarks, 24 HTML, 43
cache, 24 WML, 54
cookies, 23 code samples See examples
history, 23 configuration, 10
supported, 13 configuration icons, 10
BlackBerry Browser images connection
conversion, 15, 17 HTTP, 71
supported, 15 SSL, 11
BlackBerry Browser interface content
links, 22 conversion, 71
menus, 21 delivering content based on, 34
screen, 21 markup languages, 28
soft keys, 22 scripts, 53
BlackBerry Browser protocols, 11 server, 29, 34, 54
BlackBerry Browser push supported types, 35, 54
downloads and, 16 testing, 47, 60
BlackBerry Browser service books, 10 cookies, 23
BlackBerry Enterprise Server creating

205
BlackBerry Wireless Handheld Content Developer Guide

bitmaps, 29 HTML, 39
check boxes in HTML, 43 forms
effective images, 29 HTML, 42
forms in HTML, 42 WML, 56
links in HTML, 42
option lists in WML, 57 G
phone links, 44 gateway
WML cards, 55 WAP, 29

D H
decks, WML, 27, 54, 55, 56 handheld
depth, color, 27 model number, 36
do elements, WML, 54 simulator, 65
software versions, 34
E headers
elements accept, 34, 35
access, WML, 54 history, browser, 23
card, WML, 59 home page, 27, 55
disabling, WML, 59 HTML
do, WML, 54 alt attribute, 44
form, HTML, 42 check boxes, 43
form, WML, 56 effective links, 42
go, WML, 59 fonts, 39
horizontal rule, HTML, 42 forms, 40, 42
noop, WML, 59, 122 images, 44
sequence, WML, 56 navigation bar, 42
syntax, WML, 53 option lists, 43
timer, WML, 58 page outline, designing, 42
email address page redirection, 41
PIN mapping, 94 phone links, 44
email links, HTML, 44 script support, 40
events supported tags, 97
WML, 54, 57, 58 HTTP
examples headers, 34, 35, 72
browser detection script, 35 request, 34, 71
BrowserChannelPush.java, 78, 87
handheld color detection, 37 I
index.pl, 35 icons, 10, 66
login.html, 41, 47 images
login.wml, 60 adding in WML, 57
alignment, 57
F color, 19
fonts conversion, 15, 17

206
Index

dithering, 29 Internet Browser protocols, 12


guidelines for creating, 29 Internet Browser service books, 10
HTML, 44
monochrome, 29, 30, 37 K
placeholders, 30 keyboard, using in simulator, 66
processing, 18
scaling, 18 L
size limitations, 18 links
supported types, 15 effective creation, 27
vertical alignment, 19 email, 44
input fields, 56 HTML, 42, 44
interface phone, 44
browser screen, 29
check boxes, 54 M
links, 22
markup languages
main screen, 66
HTML support, 97
menus, 21
options, 17
option lists, 23
overview, 28
radio buttons, 54
selecting, 28
screen, 21
supported, 15
Internet Browser about, 9
Internet Browser configuration, 9 WML, 119
about, 12 WML support, 129, 175
enabling, 12 memory, 39
menus, 55
options, 25
Mobile Data Service
Internet Browser content
content filtering, 29
mobile media, 15
push applications, 71
multi-part content, 17
mobile data service
supported markup languages, 15 functionality, 12
supported scripts, 16 image conversion, 18
Internet Browser features mobile media, 15
bookmarks, 24
about, 40
cache, 24
model number, detecting, 34
cookies, 23 multi-part content, 17
history, 23
supported, 13 N
Internet Browser images
navigation bar, HTML, 42
conversion, 15, 17
network
supported, 15 connections, 9
Internet Browser interface monitoring traffic, simulator, 65
links, 22
menus, 21
O
screen, 21
soft keys, 22 option lists, 23

207
BlackBerry Wireless Handheld Content Developer Guide

HTML, 43 simulator
WML, 54, 57 icons, 65, 66
installing, 65
P keyboard, 66
phone links, HTML, 44 Mobile Data Service, 65
PIN starting, 65
email mapping, 94 trackwheel, 66
port, default, 71 using, 47, 60, 65, 66
push applications size
about, 67 content limitation, 29
central push server, 71 limitations, 27, 29
Mobile Data Service, 71 soft keys, 22
process, 71 soft keys, WML, 54, 123
troubleshooting, 94 starting simulator, 65
types, 67 supported
content types, 54
writing, 71
image types, 35
syntax
R
WML, 53
radio buttons
HTML, 43 T
WML, 54
templates, WML, 55
testing
S content, 47, 60
sample code using simulator, 47, 60, 65
color handheld detection, 37 WML pages, 46, 60
HTML login page, 41, 47 timeline events, WML, 58
HTML redirection, 41 trackwheel
Perl script, 56 implications for design, 27
WML login page, 60 using in simulator, 66
scaling images, 29
screen W
size, 27
WAP Browser about, 9
scripts WAP Browser configuration, 9
browser detection, 34, 35
about, 10
browser support for, 40
options, 25
CGI, 42
WAP Browser content
WML, 53 mobile media, 15
scrolling, trackwheel, 54, 66 multi-part content, 17
select items, WML, 54 supported markup languages, 15
server
content, 29, 34, 54 supported scripts, 16
WAP Browser features
web application, 29, 34, 54
bookmarks, 24
service books
cache, 24
configuration, 10

208
Index

cookies, 23 check boxes, 57


history, 23 decks, 27, 54, 55, 56
supported, 10, 13 disable actions, 122
WAP Browser images disable elements, 59
conversion, 15, 17, 18 events, 54, 57, 58
supported, 15 features, 53
WAP Browser interface img element, 57
links, 22 input fields, 56
menus, 21 option lists, 54
screen, 21 options lists, 57
soft keys, 22 page outline, designing, 57
WAP Browser protocols, 11 script, 53
WAP Browser push select elements, 54
downloads and, 16 sequence of elements, 56
WAP Browser service books, 10 shadowing, 59
WML supported tags, 129, 175
elements, 22
templates, 55
about, 53
text entry, 29
access element, 54, 119
actions, 54, 57
X
cards, 53, 55
XHTML, See HTML

209
BlackBerry Wireless Handheld Content Developer Guide

210
©2005 Plazmic, Inc.
Published in Canada.

You might also like