Professional Documents
Culture Documents
Adding Features........................................................................................................................................ 33
Adding and removing plugins....................................................................................................................... 33
Using custom plugins................................................................................................................................... 37
Modifying your app configuration..................................................................................................................45
App integration............................................................................................................................................ 82
BBM Social Platform.................................................................................................................................. 185
Payment Service........................................................................................................................................ 193
Push Service.............................................................................................................................................. 207
Frameworks............................................................................................................................................. 233
jQuery ....................................................................................................................................................... 233
Sencha Touch 2......................................................................................................................................... 236
Dojo Toolkit................................................................................................................................................238
Enyo 2.0.................................................................................................................................................... 241
bbUI toolkit................................................................................................................................................ 243
Documentation 5
Documentation 6
Getting Started
Learn what HTML5 and the Cordova for BlackBerry platform have to offer, and build your first app.
In this section, you can find resources to help you get started developing applications for the BlackBerry
WebWorks platform.
As of BlackBerry WebWorks 2.0, the BlackBerry 10 WebWorks SDK is now built on Apache Cordova, an open-
source development framework that lets you create applications using web technologies. Be sure to check out
some of the BlackBerry WebWorks Samples.
Although adopting Cordova as the development standard has resulted in some changes to the way WebWorks
applications are structured, the process is not complicated. Creating a BlackBerry WebWorks app involves the
following high-level steps:
1. Create your project: Use the BlackBerry 10 WebWorks SDK web tool or the command line tool to create the
folder structure and template files for your new WebWorks project,
2. Design and develop your app logic and resources: Create the HTML, CSS, JavaScript files and other
resources, or reuse existing ones, and save them in the appropriate locations in your project's /www folder.
3. Add the required plugins: A plugin represents a set of APIs that allow your app to access the features of the
platform by binding the JavaScript functions to the native methods of the device code.
4. Build and test your app: Use the web tool or the command line to test your app in a simulator or on a
device.
5. Distribute your app: Build and sign your completed app and submit it to BlackBerry World.
• portability
• integration with core BlackBerry apps
• ease of access, even when users do not have an Internet connection available
Portability
Because you create them using common web standards, BlackBerry WebWorks apps are not platform-
dependent. When you port to other mobile platforms, such as iOS or Android, you can reuse many of your
existing web assets.
By aligning with Apache Cordova for BlackBerry WebWorks 2.0, your WebWorks apps will now have an even
greater level of compatibility. Cordova provides a common development layer, and makes adapting the output
Getting Started 7
to multiple mobile platforms much simpler. You create an app using the languages you know, and Cordova
handles the bindings to the native layer of the various platforms.
You can also take advantage of popular mobile web frameworks, such as Sencha Touch, jQuery Mobile, Dojo,
and others. These frameworks provide a wide range of useful APIs that can greatly simplify cross-browser web
development. Many of these frameworks also provide a BlackBerry theme to help you achieve the same look
and feel as apps written in C/C++. See Frameworks for more information.
Integration
BlackBerry WebWorks APIs let you integrate your app with BlackBerry hardware, core apps, and services.
Standard HTML5 provides access to some BlackBerry device features, such as geolocation information and
device orientation, but the BlackBerry WebWorkss allow you to access BlackBerry specific data. For example,
you can check the battery power level, find out whether the device is holstered, or get brightness information
from the light sensor.
BlackBerry WebWorks APIs let you integrate with many of the core BlackBerry applications. For example, you
can integrate your app with BBM, Calendar, or Contacts.
You can invoke a single screen (called a card) from another app while in your app. This lets users interact with
another application to perform a specific task, such as picking a contact, composing an email, or previewing
an image, without leaving your app.
Ease of access
An app packaged with BlackBerry WebWorks can use server data if it needs to. Load times can be reduced
because most of the logic and presentation layer of the app are already on the device. If you can make your
application's resources local to the BlackBerry device, users will be able to access your content even when
they don't have an Internet connection.
When you package your web app as a BlackBerry WebWorks app, you can publish it to BlackBerry World,
where users can find and buy it. No registration fees or submission fees are required to become a BlackBerry
World vendor. To learn more about publishing your app, see BlackBerry World on the BlackBerry Developer
website.
Getting Started 8
Components of the BlackBerry 10 WebWorks SDK
The BlackBerry 10 WebWorks SDK provides the tools and plugins you need to configure and build a WebWorks
app. You create web assets using your preferred tools, and then use the SDK to package the assets into a .bar
file that can be installed onto a BlackBerry device.
Installing the BlackBerry 10 WebWorks SDK gives you:
• tools to help you create, build, test, and sign your apps
• the complete set of BlackBerry and Cordova plugins
The BlackBerry 10 WebWorks SDK is built on Apache Cordova, an open-source development framework that
lets you create applications using web technologies. This lets you take the resources that you used to create an
app for one platform, and, with some slight modifications, port that app to other platforms, such as Android or
iOS.
• create an app
• specify configuration settings
• add plugins
• build and deploy your app for testing
• build and sign your app for production
By default, the UI displays only the projects you created with the web tool in your current browser. If you have a
project that was created outside the web tool or in a different browser, you can import it at any time. For more
information about importing projects, see Importing a WebWorks 2.0 project into the SDK web tool.
Note: To use the The BlackBerry 10 WebWorks SDK web tool, your browser must accept cookies. All
WebWorks project content that appears in the tool is stored in browser cookies. Deleting these cookies
removes the project data from the web tool, but leaves the project folders intact. No project information is lost,
but you have to import your projects to work with them in the web tool.
Getting Started 9
Command Description
create
Creates a WebWorks project.
target
Manages devices and simulators for testing.
help
Describes the usage of the WebWorks commands. Entering webworks help
<command> provides usage information about that command.
build
Packages the app into a .bar file. You can choose to package the app for testing
(debug mode) or to package and sign the app for production (release mode).
run
Builds the app and deploys it onto a BlackBerry device. You can choose to
deploy the app for testing (debug mode) or sign and deploy the app for
production (release mode).
emulate
Builds the app and deploys it onto the simulator for testing.
plugin
Manages the app's plugins.
serve
Serves the app so you can preview it in your local browser.
Plugins represent the layer that connects JavaScript to the native C/C++ layer of the BlackBerry 10 OS. They
allow you to access the native functionality of the device (for example, accessing accelerometer data, or using
the camera) without the need to code in the device's native language.
• Use the methods, properties, and events for an API in your JavaScript code as described in the API
Reference.
• Add the appropriate plugins to your app to bind your JavaScript code to the native C/C++ code.
Note: Some plugins require you to add certain permissions to the app configuration in order to access native
functionality. In most cases, when you add a plugin that requires a permission, the permission is added
Getting Started 10
automatically to the configuration by the tools. In some cases, however, the permission is only required to
access a subset of the native functionality. In these cases, the permission is not added automatically; you must
add the permission yourself. For more information about adding permissions, see Adding and removing app
permissions.
Plugin Description
com.blackberry.app Provides basic app support.
com.blackberry.bbm.platform Lets you access the social features and functionality of BBM.
com.blackberry.connection Lets you access the cellular and Wi-Fi connection information for
the BlackBerry device.
com.blackberry.identity Provides information about the user's identity and accounts.
com.blackberry.invoke Lets your app invoke and interact with other apps on the device.
com.blackberry.invoke.card Lets your app invoke a screen of another app on the device.
com.blackberry.invoked Lets your app be invoked by other apps on the device.
com.blackberry.io Provides access to the unsandboxed file systems.
com.blackberry.io.filetransfer Lets your app upload and download files to/from a remote server.
com.blackberry.notification Lets your app to provide notifications to the user.
com.blackberry.push Lets you access the BlackBerry push architecture to receive push
content in your app.
Getting Started 11
Plugin Description
Required permissions:
• sys_use_consumer_push
• run_when_backgrounded
com.blackberry.sensors Lets you get access to system level sensors and attributes of the
BlackBerry device.
com.blackberry.system Lets you access system level functions and attributes of the
BlackBerry device.
com.blackberry.ui.contextmenu Lets you control whether context menus are enabled, listen to
events, add items to appear based on the context, and set the
theme of the context menu.
com.blackberry.ui.cover Lets you modify the app's window cover, which is displayed when
the app is in thumbnail mode.
com.blackberry.ui.dialog Lets you manipulate system dialog boxes.
com.blackberry.ui.toast Lets you display system toasts in your app.
Plugin Description
org.apache.cordova.device-motion Captures device motion in the x, y, and z directions.
org.apache.cordova.camera Provides access to the device's default camera application.
org.apache.cordova.media-capture Provides access to the device's audio, image, and video capture
capabilities.
org.apache.cordova.device-orientation Obtains the direction that the device is pointing.
org.apache.cordova.network- Provides information about the device's cellular and Wi-Fi
information connection.
org.apache.cordova.contacts Provides access to the device's contact database.
org.apache.cordova.device Describes the device's hardware and software.
org.apache.cordova.file Provides the functionality to read, write, and navigate file system
hierarchies.
Getting Started 12
Plugin Description
org.apache.cordova.geolocation Provides access to location information based on the device's GPS
sensor or inferred from network signals.
org.apache.cordova.inappbrowser Provides a browser view that displays when calling
window.open(), or when opening a link formed as <a
target="_blank">.
org.apache.cordova.media Lets your app play back audio and video files on a device.
org.apache.cordova.dialogs, Lets your app create visual, audible, and tactile notifications.
org.apache.cordova.vibration
org.apache.cordova.splashscreen Lets your app hide and show the splashscreen.
System requirements
Before downloading and using the BlackBerry 10 WebWorks SDK, make sure that your system meets the
following requirements:
Getting Started 13
BlackBerry 10 WebWorks SDK browser requirements
Note the following requirements if you intend to use the BlackBerry 10 WebWorks SDK web tool to configure
and build your projects:
Supported browsers
The BlackBerry 10 WebWorks SDK web tool has been tested against the following browsers:
• Google Chrome
• Mozilla Firefox
• Safari (version 6 or later)
• Internet Explorer (version 8 or later)
Cookie settings
To use the The BlackBerry 10 WebWorks SDK web tool, your browser must accept cookies. All WebWorks
project content that appears in the tool is stored in browser cookies. Deleting these cookies removes the
project data from the web tool, but leaves the project folders intact. No project information is lost, but you have
to import your projects to work with them in the web tool.
For more information about importing projects, see Importing a WebWorks 2.0 project into the SDK web tool.
Note:
If you are installing to Mac OS X Mountain Lion (10.8) or later, you will need to change you system
preferences to successfully install the SDK. To change your system settings:
Note:
If you are installing to Ubuntu, after downloading the installer, you'll need to make it executable by running
the following commands:
Getting Started 14
Note: The BlackBerry ID token is used to create the debug token that allows you to install and test an
unsigned app on a BlackBerry 10 device. If you don't have a BlackBerry ID token, you cannot test your app
on a device.
Note: Using the BlackBerry ID token is new in BlackBerry WebWorks 2.0. If you are updating an app created
using an earlier version of WebWorks, you can link your legacy token (barsigner.csk) to your new BlackBerry ID
token (bbidtoken.csk) to maintain continuity. For more information, see Linking your BlackBerry ID token to a
signing authority account.
The BlackBerry ID token is included in the keystore file you downloaded. The Signing Authority Service uses
this token for authentication when you sign your app using the associated developer certificate. Signing your
app helps verify the integrity and authenticity of your app to users and to the BlackBerry 10 OS. The
BlackBerry 10 WebWorks SDK also uses the BlackBerry ID token to allow you to test your unsigned apps on a
BlackBerry 10 device.
Your BlackBerry ID token is valid for one year. When it expires, you need to create a new one.
To sign apps and create debug tokens, you must use your BlackBerry ID token to create a developer
certificate. Each time you request a new BlackBerry ID token, you must create a new developer certificate.
1. On the Start menu, click BlackBerry >BlackBerry WebWorks <version>. A new browser window opens,
displaying the BlackBerry 10 WebWorks SDK web tool.
2. In the navigation panel, click Certificate.
3. In the Location field, enter the full path to your bbidtoken.csk file.
4. Click Add Signing Key. The signing key (bbidtoken.csk) is installed to the following location:
Getting Started 15
When the signing key has been installed, the Developer Certificate fields appear.
5. In the Keystore Password field, enter your BlackBerry ID token password.
6. In the Company name field, type the name of the organization you want to associate with the developer
certificate.
7. Click Create Certificate. The developer certificate (the author.p12 file) is created in the same location as
your signing key.
Create your developer certificate from the command line
When you run this command, the author.p12 file is created in the same folder where you installed the
bbidtoken.csk in Step 1.
Parameters Description
-genkeypair
Generates a key pair that consists of a private key and a public
key.
-storepass <keystore_pw>
Specifies the password that is used to control access to the
keystore, which is your BlackBerry ID token password.
-dname
Specifies the name to associate with the certificate that the
tool creates.
During the signing process, your computer connects to the Signing Authority Service. If your computer
connects to the Internet through a proxy server, you should append the options in the following table to your
commands.
Getting Started 16
Option Description
-proxyhost <host> This option specifies the network host that provides the proxy service.
The value can be an IP address or a fully qualified domain name.
-proxyport <port> This option specifies the port number on your proxy server through
which blackberry-signer or blackberry-
debugtokenrequest should communicate with the Signing Authority
Service.
-proxyusername This option allows you to provide your user name if your proxy server
requires authentication.
<user name>
-proxypassword This option allows you to provide your password if your proxy server
requires authentication.
<password>
A new project includes all the basic resources required to function as a complete app. The folder structure of a
project includes a /www folder. This folder is the working directory for your app. All project resource files should
be stored in the /www folder, or in the appropriate subfolder. See Folder structure of a WebWorks project for the
complete folder structure of a WebWorks project.
Note: By default, your app has no access to any of the Cordova or WebWorks APIs. You need to add plugins to
access the functionality you want your app to have. For more information about plugins and how to add them,
see Adding and removing plugins.
Getting Started 17
1. On the Start menu, click BlackBerry >BlackBerry WebWorks <version>. A new browser window opens,
displaying the BlackBerry 10 WebWorks SDK web tool.
2. In the navigation panel, click [+] beside the Projects heading.
3. In the Project Name field, enter your application's name.
4. In the Project Path field, enter a project path.
5. Click Create.
1. On the command line, navigate to the folder where you installed the BlackBerry WebWorks SDK.
2. Run the following command to create a WebWorks project:
For example, the following command creates a project called My App in the c:\webworks-apps\myapp folder:
Parameter Description
<path>
Specifies the home folder for your project. The tool
creates this folder for you and does not overwrite an
existing folder; if you specify an existing folder, the project
is not created.
<app-id>
Specifies a unique identifier for the app. If provided, this
value is used to populate the <id> element in the
config.xml file.
Getting Started 18
Parameter Description
<app-name>
Specifies the name for the app. To specify a name with
spaces in it, enclose the value in quotation marks ("). If
provided, this value is used to populate the <name>
element in the config.xml file.
This parameter is optional.
Once your project is created, you may want to edit the configuration information, for example, to specify a
particular orientation or background color. For more information, see Modifying your app configuration.
1. On the Start menu, click BlackBerry >BlackBerry WebWorks <version>. A new browser window opens,
displaying the BlackBerry 10 WebWorks SDK web tool.
2. In the navigation panel, click the arrow icon beside the Projects heading.
3. In the Project Path field, enter the complete path to the project.
4. Click Open.
Folder Description
project_root/ This folder is the root folder, which you specify when you create your project.
This folder contains the master config.xml file.
www/ This folder contains all your project resources, including the index.html file,
which is the starting page for your app. It also contains subfolders for various
resources, including CSS and JavaScript files, as well as any other resources you
might add.
Getting Started 19
Folder Description
merges/ This folder contains platform-specific resources. It should contain a subfolder for
each platform you are creating your app for, which contains a duplicate of
the /www folder structure.
For example, you can store a platform-specific JavaScript file in the project_root/
merges/blackberry10/www/js subfolder. When you build the app for BlackBerry
10, that JavaScript file is used in place of the JavaScript file of the same name in
the project_root/www/js folder.
platforms/ The SDK uses this folder to maintain platform-specific versions of your project.
A blackberry10 folder is automatically created in this folder, and you can add
folders for additional platforms, such as Android or iOS.
When you build your app for a specific platform, the contents of the www/ folder
are copied to the appropriate platform-specific folder.
plugins/ This folder contains any plugins you add to your project. By default, this folder is
empty.
Note: Before you start, make sure you have the necessary tools installed. For more information, see Setting up
your tools.
Getting Started 20
1. On the Start menu, click BlackBerry WebWorks <version>. A new browser window opens, displaying the
BlackBerry 10 WebWorks SDK web tool.
2. Click [+] beside the Projects heading in the navigation panel.
3. Enter Hello World in the Project Name field.
4. Enter C:\TestApps in the Project Path field.
5. Click Save.
The default app project includes all the necessary artifacts to function as a complete app.
• Device Password is enabled ( Settings > Security and Privacy > Device Password )
• Development Mode is enabled ( Settings > Security and Privacy > Development Mode )
1. In the BlackBerry 10 WebWorks SDK web tool, under your project's name in the navigation panel, click
Build.
2. Select Debug Mode.
3. Select Simulator.
4. Click Build & Install.
The tool packages your app into a .bar file, installs and launches it on your simulator.
• Development Mode is enabled ( Settings > Security and Privacy > Development Mode )
• Debug token is installed and valid
1. In the BlackBerry 10 WebWorks SDK web tool, under your project's name in the navigation panel, click
Build.
2. Select Debug Mode.
3. Select Device.
4. Enter your device password.
5. Enter your keystore password, which you defined when you registered your BlackBerry ID token. If you have
not yet registered your BlackBerry ID token, see Set up your computer for testing and signing.
6. Click Build & Install.
Once the app successfully installs on your device and before the app starts for the first time, a dialog box
appears. Click OK on this dialog box to permit the app to access various resources on your device. Also, each
time the app opens, a dialog box appers to inform you that Web Inspector is enabled.
Getting Started 21
Getting Started 22
Porting and Upgrading
Learn how to upgrade from previous versions of BlackBerry WebWorks, port your existing Cordova application,
and port to other platforms.
In this section, you can find out how to upgrade from previous versions of BlackBerry WebWorks, port your
existing Cordova application, and port to other platforms.
But don't worry. Migrating your app to the new Cordova-based WebWorks world is pretty simple. Migrating your
app involves the following steps:
You can find the SDK here. For additional information about the tools you need and how to set them up, see
Setting up your tools.
Note: The signing process has changed for BlackBerry WebWorks 2.0. Unlike previous versions, where a
separate token was required to create the developer certificate (used for code signing) and debug token (used
for testing unsigned apps on the device), now a single token is required. This token is associated with your
BlackBerry ID.
• For more information on changes to the signing process, see Changes to code signing.
• For more information about getting set up for testing and signing with BlackBerry WebWorks 2.0, see Set up
your computer for testing and signing.
Use the BlackBerry WebWorks GUI tool to create a new project. Once created, the new project includes a
default app with all the basic resources required to function as a complete app. The folder structure of your
new project includes a /www folder. This folder is the working directory for your application.
For more information about creating a new BlackBerry WebWorks 2.0 project, see Creating a WebWorks
project.
Delete the template project resources in your new BlackBerry WebWorks 2.0 project folders and paste your
application resources in their place. All your HTML files should be placed in the /www folder; your CSS,
JavaScript, and image files can be placed in the appropriate subfolders of the /www folder.
Note: You can choose to copy over your existing config.xml file, or build a new one based on the template
config.xml. However, in either case, you should be aware that the structure of the config.xml file has changed
slightly in BlackBerry WebWorks 2.0. As a result, you may need to make some manual modifications to your
config.xml file. For more information on changes to the config.xml file, see Changes to the config.xml file.
Unlike previous versions of BlackBerry WebWorks, BlackBerry WebWorks 2.0 uses plugins to add APIs to your
app. A plugin is a set of APIs you can use to access features of the platform. You'll need to add a plugin for
each of the BlackBerry WebWorks APIs you use in your app. These plugins correspond to the <feature>
elements you added to your old config.xml file.
For more information about plugins, including which you should add and how to add them, see Changes to the
way you add APIs to your app.
Once you have copied over your resources and added the necessary plugins to your project, there are a few
minor code changes that may be required so that your code is compatible with the new architecture:
To get all the details on updating your code, see Coding differences.
With the previous steps completed, you can begin building and testing your app to make sure it is functioning
as expected.
Use the BlackBerry WebWorks GUI tool to build your app in debug mode.
BlackBerry WebWorks 2.0 includes a number of improvements to the build process. Now, with a single
command, you can create and install a debug token on a BlackBerry 10 device, and build, install, and launch
your app on the device.
To align with Apache Cordova, BlackBerry WebWorks 2.0 uses plugins, which contain an API or a set of APIs,
to add features and functionality to your app. When you installed the BlackBerry WebWorks SDK, a number of
plugins were installed with it, each providing access to a different feature of the platform.
In your existing BlackBerry WebWorks project, you handled access to the various APIs of the BlackBerry
platform by adding <feature> tags to your config.xml file. At build time, the packager looked at the
<feature> elements in the config.xml file to determine which BlackBerry WebWorks APIs to bundle with the
app.
In BlackBerry WebWorks 2.0, however, you access an API by adding the appropriate plugin to your project.
When you add a plugin, the WebWorks tools add the plugin to the /plugins folder. You can determine which
plugins you need to add by looking at the <feature> elements in your old config.xml file; each <feature>
element will map to a corresponding BlackBerry plugin.
Plugins can be added either from the BlackBerry 10 WebWorks SDK web tool, or from the command line.
• To use the BlackBerry 10 WebWorks SDK web tool, click BlackBerry WebWorks <version> on the Start
menu to open the tool, then click the Plugins button under your project's name in the navigation panel.
• To use the command line, navigate to your project folder and then run:
You should be aware that if you used HTML5 notifications in your previous app, you will need to add a plugin to
access this functionality, even though it required no <feature> element previously. To access the same
functionality, add the com.blackberry.notification plugin to your app.
The following table outlines how BlackBerry WebWorks plugins map to the <feature> element entries in
your existing config.xml file.
If you added this <feature> element: You'll need to add this plugin:
<feature id="blackberry.app" /> com.blackberry.app
<feature com.blackberry.bbm.platform
id="blackberry.bbm.platform" />
<feature com.blackberry.connection
id="blackberry.connection" />
<feature id="blackberry.identity" /> com.blackberry.identity
Although BlackBerry WebWorks and BlackBerry WebWorks 2.0 both use a config.xml file to store configuration
information for your project, the way in which they are created and used differs slightly.
If you need to manually edit the config.xml file, you can find it your project's root folder.
With BlackBerry WebWorks 2.0, there is now little need for you to edit the config.xml file manually, as most of
the configuration settings can be manged through the BlackBerry 10 WebWorks SDK web tool. A config.xml
file is now created automatically and prepoulated with template configuration information when you create
your project.
You can use the BlackBerry 10 WebWorks SDK web tool to customize the contents of the file. Clicking
BlackBerry WebWorks <version> on the Start menu opens the BlackBerry 10 WebWorks SDK web tool. You
can click the Configuration button under your project's name in the navigation panel to view and edit adjust
many of your app's configuration settings, including author and description information, orientation,
background color, and more. The web tool will now also allow you to add your plugins, and allows you to set any
necessary plugin permissions.
The only instance where you need to manually edit the config.xml file is if you want to set up your app as an
invocation target. In this case, you must still manually add the <rim:invoke> element and its children to
register the app as an invocation target and to define which file types your app can handle.
If you intend to reuse your existing config.xml file, there is no longer any need to add <feature> elements to
the config.xml file. The BlackBerry WebWorks tools will now handle adding these at build time, based on which
plugins you've added to your project. For best results, once you have added the required plugins to your
project, you should remove all <feature> elements from your existing config.xml.
The way in which you set the configuration parameters associated with the Application API (for example, to
define the app orientation or background color) has changed. Previously, you would define these by adding the
following elements to your config.xml file:
<feature id="blackberry.app">
<param name="orientation" value="portrait" />
</feature>
In BlackBerry WebWorks 2.0, you must now define these parameters using <preference> elements, which
are children of the top-level <widget> element. For example, to set the orientation as in the example above,
your config.xml file should now contain the following code:
<widget>
.
.
.
<preference name="orientation" value="portrait" />
</widget>
If you choose, you can set all preferences directly in the BlackBerry 10 WebWorks SDK web tool.
Coding differences
Although BlackBerry WebWorks has been significantly re-architected to align with the Cordova standards, if
you have previously created a WebWorks app for BlackBerry 10, there are really only a few small changes
you'll need to make to your HTML and JavaScript code to make it compatible.
In BlackBerry WebWorks apps, you needed to include webworks.js to launch the BlackBerry WebWorks
application runtime. For example:
In BlackBerry WebWorks 2.0, you include cordova.js instead. You should replace all instances of webworks.js
with cordova.js. For example:
In BlackBerry WebWorks apps, your app needed to listen for the webworksready event, and could not call
any BlackBerry WebWorks APIs until the event had occured. For example:
document.addEventListener('webworksready', function(e) {
.
.
.
}
In a BlackBerry WebWorks 2.0 project, you'll need to listen for the deviceready event instead. You should
replace all instances of webworksready with deviceready. For example:
document.addEventListener('deviceready', function(e) {
.
.
.
}
Signing apps in BlackBerry WebWorks 2.0 is different from previous versions of BlackBerry WebWorks. The
signing process has been streamlined; simply building the app in release mode results in a signed application.
More significantly, BlackBerry WebWorks 2.0 uses the BlackBerry ID token for signing, which associates your
keystore with your BlackBerry ID.
For more information about getting and using the BlackBerry ID token, see Set up your computer for testing
and signing.
If you are updating an earlier version of your app that was signed using a signing authority token, you can link
that token to your BlackBerry ID token (bbidtoken.csk). By linking these accounts, your updated BlackBerry
WebWorks 2.0 app keeps continuity with the previous versions of your app and appears to end users as an
update, rather than a new app altogether.
You can link your BlackBerry ID token to an existing signing authority account. Linking the two accounts allows
you to produce .bar files with the same Package-Author-Id, Package-Id, and Application-Id, so that you can
create upgraded versions of your existing app.
1. On the Start menu, click BlackBerry >BlackBerry WebWorks <version>. A new browser window opens,
displaying the BlackBerry 10 WebWorks SDK web tool.
2. In the navigation panel, click Certificate.
3. In the Location field, enter the full path to your barsigner.csk file.
4. Click Add Signing Key. The Link Signing Keys fields appear.
5. In the BBID Signing Token Location field, enter the full path to your bbidtoken.csk file.
6. In the Barsigner Password field, enter the password associated with your barsigner.csk.
7. In the BBID Signing Token Password field, enter your BlackBerry ID token password.
8. Click Link Signing Keys. The developer certificate (the author.12 file) is created in the same location as
your signing key.
The documentation for previous releases of BlackBerry WebWorks placed a lot of emphasis on the Ripple
emulator. If you used the Ripple emulator before, you'll probably notice that it is no longer discussed within the
BlackBerry WebWorks documentation. The reason for this is that BlackBerry has recently donated Ripple to
the Apache open source comunity. As a result, BlackBerry is no longer in control of Ripple development or
release cycles.
Work is still progressing on Ripple within the Apache community. At the moment, however, Ripple is not
compatible with Apache Cordova 3.0, upon which BlackBerry WebWorks is based, so it cannot currently be
used to test your BlackBerry WebWorks app. For future updates on Ripple, see http://
ripple.incubator.apache.org/#download.
To use a BlackBerry WebWorks command, run webworks <command>, where <command> is one of the
following:
• The build command builds your app in release mode or debug mode, without deploying it to a simulator
or device.
Both the emulate and run commands also let you specify whether you want to skip the build or launch steps.
For example, the following example adds the BlackBerry Application API to your app.
Parameters Description
<id>
Specifies the unique identifier for the plugin.
<path>
Specifies the path to the plugin on your local file
system.
<uri>
Specifies the remote location for the plugin.
Visit http://plugins.cordova.io/ to download the plugins and learn how to add them using the Cordova command
line interface.
To add an additional platform, use the cordova platform add command. For a complete porting
walkthrough, see the Apache Cordova documentation.
Note: You can skip the Create the App step since you have already created your app using the BlackBerry
WebWorks SDK.
Note: Adding plugins for other platforms may require you to make some changes to your source code.
Using PhoneGap
PhoneGap is an alternative tool for packaging and porting your app to multiple platforms. It is also based on
Apache Cordova, so your source code will not need to be changed. PhoneGap can be used either as a set of
command line tools or as a web service that packages and builds your app remotely. For a complete overview,
see the PhoneGap documentation.
In this section, you'll learn how to add plugins to your app and implement unique BlackBerry features.
Each plugin you add to your project is packaged with your app. To keep the size of your app small, add only the
plugins that you need.
When you install the BlackBerry 10 WebWorks SDK, the installation includes the BlackBerry and Cordova
plugins. You can find them in the plugins/ subfolder of the BlackBerry 10 WebWorks SDK installation folder.
You can create your own plugins or access plugins created by the WebWorks community to access native APIs
that are not available through the BlackBerry and Cordova plugins. For more information, see Using custom
plugins.
1. On the Start menu, click BlackBerry WebWorks <version>. A new browser window opens, displaying the
BlackBerry 10 WebWorks SDK web tool.
2. Navigate to your project and click Plugins.
3. Enter the ID or URL of the plugin in the Plugin Name or URL field.
4. Click Add Plugin.
Add a plugin
You can use the plugin add command to add a plugin to your project. You can add a plugin by ID, path, or
URI.
Adding Features 33
2. Run the following command:
For example, the following command adds the BlackBerry Application API to your app.
Parameter Description
<id>
The unique identifier for the plugin.
<path>
The path to the plugin on your local file system.
<uri>
The remote location for the plugin.
Remove a plugin
You can use the plugin rm command to remove a plugin from your project.
Parameters Description
<id>
Specifies the unique identifier for the plugin.
Adding Features 34
2. Run the following command:
webworks plugin ls
Plugin Description
com.blackberry.app Provides basic app support.
com.blackberry.bbm.platform Lets you access the social features and functionality of BBM.
com.blackberry.connection Lets you access the cellular and Wi-Fi connection information for
the BlackBerry device.
com.blackberry.identity Provides information about the user's identity and accounts.
com.blackberry.invoke Lets your app invoke and interact with other apps on the device.
com.blackberry.invoke.card Lets your app invoke a screen of another app on the device.
com.blackberry.invoked Lets your app be invoked by other apps on the device.
com.blackberry.io Provides access to the unsandboxed file systems.
com.blackberry.io.filetransfer Allows you to upload and download files to/from a remote server.
com.blackberry.notification Lets your app to provide notifications to the user.
Adding Features 35
Plugin Description
com.blackberry.push Lets you access the BlackBerry push architecture to receive push
content in your app.
Required permissions:
• sys_use_consumer_push
• run_when_backgrounded
com.blackberry.sensors Lets you get access to system level sensors and attributes of the
BlackBerry device.
com.blackberry.system Lets you access system level functions and attributes of the
BlackBerry device.
com.blackberry.ui.contextmenu Lets you control whether context menus are enabled, listen to
events, add items to appear based on the context, and set the
theme of the context menu.
com.blackberry.ui.cover Lets you modify the app's window cover, which is displayed when
the app is in thumbnail mode.
com.blackberry.ui.dialog Lets you manipulate system dialog boxes.
com.blackberry.ui.toast Lets you display system toasts in your app.
Plugin Description
org.apache.cordova.device-motion Captures device motion in the x, y, and z directions.
org.apache.cordova.camera Provides access to the device's default camera application.
org.apache.cordova.media-capture Provides access to the device's audio, image, and video capture
capabilities.
org.apache.cordova.device-orientation Obtains the direction that the device is pointing.
org.apache.cordova.network- Provides information about the device's cellular and Wi-Fi
information connection.
org.apache.cordova.contacts Provides access to the device's contact database.
org.apache.cordova.device Describes the device's hardware and software.
Adding Features 36
Plugin Description
org.apache.cordova.file Provides the functionality to read, write, and navigate file system
hierarchies.
org.apache.cordova.geolocation Provides access to location information based on the device's GPS
sensor or inferred from network signals.
org.apache.cordova.inappbrowser Provides a browser view that displays when calling
window.open(), or when opening a link formed as <a
target="_blank">.
org.apache.cordova.media Lets your app play back audio and video files on a device.
org.apache.cordova.dialogs, Lets your app create visual, audible, and tactile notifications.
org.apache.cordova.vibration
org.apache.cordova.splashscreen Lets your app hide and show the splash screen.
You create a custom plugin in C/C++, the native development languages for BlackBerry 10 OS, and then you
wrap it in JavaScript. When you build and package your web app for BlackBerry, you include the plugin source
files along with other assest of your app in the package. This enables you to use JavaScript to access the
plugin's functionality from within your app at any time. Using the extended function, you can pass arguments
and handle return values, like you would in any native BlackBerry 10 app.
An Apache Cordova plugin for BlackBerry 10 is composed of a Cordova JavaScript interface and native
implementations of a BlackBerry specific plugin interface that the JavaScript calls into.
JavaScript is the entry point for the plugin. The JavaScript interface is front-facing and is the most important
part of your Cordova plugin. In a Cordova plugin for BlackBerry 10, the native and JavaScript code
Adding Features 37
communicate with each other through a framework provided by JNEXT. Every plugin must also include a
plugin.xml file.
You can structure your plugin's JavaScript according to your preference. However, you must use the
cordova.exec function to communicate between the Cordova JavaScript and the BlackBerry native
environment. The cordova.exec function has the following signature:
To demonstrate how to create a Cordova plugin for BlackBerry 10, let's use a very simple plugin named Echo.
The Echo plugin demonstrates how to invoke native functionality from JavaScript. The plugin passes a string
from JavaScript and sends it into the native environment. The native code then returns the same string (that is,
echoes it) back into the callbacks inside the plugin's JavaScript.
Note: Although this Echo tutorial is useful to help you understand the steps required to create a custom plugin,
it is intentionally basic, and not intended as a template for you to follow. When you are ready to create your own
custom plugin, we recommend that you start with the BlackBerry plugin template, which you can find here.
Below is the JavaScript sample code showing the use of the cordova.exec function. We attach the plugin to
window, specifically to the echo function:
Adding Features 38
Let's take a detailed look at the last three arguments to the exec function. Here, the exec function is calling
the "Echo" service, requesting the "echo" action, and passing the array containing the "str" argument. The
string str represents the string that is to be echoed and is the first parameter into the window.echo
function. Note that the success callback passed into the exec function is simply a reference to the callback
function that window.echo takes (it's the second parameter).
We do a bit more for the error callback. If the native side fires off the error callback, we simply invoke the
success callback and pass into it a default string to echo back and indicate that an error has occured (using
the string 'Nothing to echo.').
window.echo("echome", function(echoValue) {
alert(echoValue == "echome"); // should alert true, if there is no
error
});
We can now use what we learned about the cordova.exec function and create an Echo plugin for the
BlackBerry 10 platform.
The JavaScript portion of your plugin must contain a client.js and an index.js file:
• client.js – This is considered the client side and contains the API that a Cordova application can call. The
API in client.js makes calls to index.js. The API in client.js also connects callback functions to the events
that fire the callbacks.
• index.js – This is considered the server side. Cordova loads index.js and makes it accessible through the
cordova.exec bridge. The client.js file makes calls to the API in the index.js file, which in turn makes
calls to JNEXT to communicate with the native side.
module.exports = {
echo: function (data, success, fail) {
exec(success, fail, service, "echo", { data: data });
}
};
In client.js you invoke the exec() function and provide the necessary arguments. In the Echo plugin, we
have the following in the client.js file:
module.exports = {
Adding Features 39
echo: function (data, success, fail) {
exec(success, fail, service, "echo", { data: data });
}
};
1. In your constructor, use the init() function to perform some key operations:
a) Specify the required module exported by the native side. The name of the required module must match
the name of a shared library file (.so file).
JNEXT.require("libecho")
a) Create an object by using the acquired module and save the ID that's returned by the call.
self.m_id = JNEXT.createObject("libecho.Echo");
Here is the constructor from our sample Echo plugin:
var echo;
JNEXT.Echo = function () {
var self = this,
hasInstance = false;
self.init = function () {
if (!JNEXT.require("libecho")) {
return false;
}
self.m_id = JNEXT.createObject("libecho.Echo");
JNEXT.registerEvents(self);
};
self.m_id = "";
self.getInstance = function () {
if (!hasInstance) {
self.init();
hasInstance = true;
Adding Features 40
}
return self;
};
};
2. When your application calls the echo function in client.js, that call in turn calls the echo function in
index.js, where the PluginResult object sends a response (data) back to client.js. Since the args
argument passed into the functions was converted by JSON.stringfy() and encoded as a
URIcomponent, you must decode the data before you send it with the response:
data = JSON.parse(decodeURIComponent(args.data));
Now we are ready to send the data back. Here's how it turns out when you put it all together:
module.exports = {
To create the native portion of your plugin, in the BlackBerry 10 Native SDK, do the following:
1. On the File menu, click New > BlackBerry Project > Native Extension > BlackBerry WebWorks and click
Next.
2. In the Project name field, type a name for the project (for example, echo) and click Finish.
The SDK creates a native extension project and displays it in your Workbench.
System requirements
To create custom plugins to use with your web apps on BlackBerry 10 OS, you require the following:
The native extension project you create using the BlackBerry Project wizard in the IDE contains code for a
sample plugin called the memory extension plugin. Replace or modify the files in the project to add functionaly
according to your needs:
Adding Features 41
The native interface for the JNEXT extension can be viewed in the plugin header file located in the public folder
of your project. It also contains constants and utility functions that can be used in your native code. Your plugin
must be derived from JSExt, which is defined in plugin.h. That is, you must implement the following class:
class JSExt
{
public:
virtual ~JSExt() {};
virtual string InvokeMethod( const string& strCommand ) = 0;
virtual bool CanDelete( void ) = 0;
private:
std::string m_id;
};
Therefore, your extension should include the plugin.h header file. In the Echo example, you use JSExt as
follows in the echo_js.hpp file:
#include "../public/plugin.h"
#include <string>
#ifndef ECHO_JS_H_
#define ECHO_JS_H_
#endif // ECHO_JS_H_
• m_id: The m_id is an attribute that contains the JNEXT ID for this object. The ID is passed to the class as
an argument to the constructor. It is needed to trigger events on the JavaScript side from native.
• CanDelete(): The CanDelete() method is used by JNEXT to determine whether your native object can
be deleted.
• InvokeMethod(): The InvokeMethod() function is called when JavaScript invokes a method of this
particular object. The only argument this function takes is a string passed from JavaScript that
InvokeMethod() parses in order to determine which method of the native object should be executed.
Now we implement these functions in echo_js.cpp. For the Echo example, we implement the
InvokeMethod() function as follows:
Adding Features 42
int index = command.find_first_of(" ");
string strCommand = command.substr(0, index);
string strValue = command.substr(index + 1, command.length());
Your native plugin must also implement the onGetObjList() and onCreateObject() callback
functions:
The onGetObjList() function returns a comma-separated list of classes supported by JNEXT. JNEXT
uses this function to determine the set of classes that it can instantiate. In our Echo plugin, we have the
following in echo_js.cpp:
char* onGetObjList() {
static char name[] = "Echo";
return name;
}
• extern JSExt* onCreateObject(const string& strClassName, const string&
strObjId);
The onCreateObject() function takes two parameters. The first parameter is the name of the class
requested to be created from the JavaScript side. Valid names are those that are returned in
onGetObjList(). The second parameter is the unique object ID for the class. This method returns a
pointer to the created plugin object. In our Echo plugin, we have the following in echo_js.cpp:
You can place the artifacts of the plugin, which include the plugin.xml file, the source files (JavaScript, C++),
and the binary files (*.so), in any directory structure, as long as you specify the file locations in the plugin.xml
file. Below we show a typical structure:
Note: The structure below uses bold text for folder names and plain text for file names.
• your_project_ folder
• plugin.xml
Adding Features 43
• www
• client.js
• src
• blackberry10
• index.js
• *.cpp (native files)
• *.hpp (native files)
• device
The plugin.xml file contains the namespace of the extension and other metadata. Define the namespace and
specify other metadata for the Echo plugin as follows:
<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
id="org.apache.cordova.blackberry.echo"
version="1.0.0">
<js-module src="www/client.js">
<merges target="navigator" />
</js-module>
<platform name="blackberry10">
<source-file src="src/blackberry10/index.js" />
<lib-file src="src/blackberry10/native/device/libecho.so"
arch="device" />
<lib-file src="src/blackberry10/native/simulator/libecho.so"
arch="simulator" />
<config-file target="www/config.xml" parent="/widget">
<feature name="org.apache.cordova.blackberry.echo"
value="org.apache.cordova.blackberry.echo" />
</config-file>
</platform>
</plugin>
Community plugins
BlackBerry WebWorks is an open source project. Members of the open source community can create their
own plugins to extend the functionality of the SDK and can make those plugins available to the wider
community. These plugins provide access to native libraries that are not otherwise available through the
WebWorks or Cordova APIs, or through standard HTML5 functions.
Feel free to use any of the available community plugins in your WebWorks app, or contribute your own custom
plugin to the community.
Adding Features 44
Modifying your app configuration
When you create a WebWorks project, the tools create a default config.xml file for you, with some entries
prepopulated. The config.xml contains some entries that define meta data about your app (such as the app ID
and app description) and you (such as author name, company, and so on). The config.xml file also defines
some app features, behaviors, and device and Internet access permissions.
You can modify these configuration values at any time, either by using the BlackBerry 10 WebWorks SDK web
tool, or by manually modifying the config.xml file.
To set your app preferences with the BlackBerry 10 WebWorks SDK web tool:
1. On the Start menu, click BlackBerry >BlackBerry WebWorks <version>. A new browser window opens,
displaying the BlackBerry 10 WebWorks SDK web tool.
2. Navigate to your project and click Config.
3. Complete the fields for the preferences you would like to set.
The following table lists the available preferences and their descriptions.
Preference Description
Splash Screen Image The image that's displayed when the app is opened.
Adding Features 45
Preference Description
Author Email The email address that is associated with the author.
Main URL The start page that the BlackBerry WebWorks app displays when it
runs.
Orientation The orientation for screens in your app. The orientation can be
default (orientation changes according to the orientation of the
device), portrait, or landscape. If no value is specified, the
orientation is set to default.
Autohide Splash Screen Hides the splash screen for your application. When this setting is
disabled, the splash screen is displayed until
splashscreen.hide() is invoked in your code.
Hide Keyboard Form Bar Hides the row of buttons (Previous, Next, and Submit) that is
displayed when an <input> element on the current page of the
app gets focus.
Enable Child Browser Enables your app to open child browser windows. A child window is
launched when the content attempts to open a resource in a new
window or tab (by using window.open(), or by specifying
_blank as the target of an anchor).
Enable Popup Blocker When selected, prevents the app from displaying popups.
Enable Web Security Enables web security. Disabling web security allows you to access
remote content from unknown sources.
Adding Features 46
Preference Description
Enable Disk Cache Enables WebView caching, which prevents the app from issuing
multiple network requests for the same resource.
By default, BlackBerry WebWorks apps cannot access data from external resources. For example, a
BlackBerry WebWorks app cannot retrieve an HTML webpage, unless you configure the app to allow access.
To allow access to external resources, you must specify access permissions to define the list of domains that
your app is allowed to access.
Whenever your app retrieves content from external resources, consider the following best practices to make it
as secure as possible:
• Provide JavaScript access to sensitive APIs only to trusted and secure websites.
• Use the same precautions that you would use for a hosted website to protect against users with malicious
intent.
Adding Features 47
• Protect your communication channel by using HTTPS when you expose sensitive APIs to the domain.
In the following example, we use the access element to specify that the site is accessed over HTTPS:
If your app is designed to access data from an unknown or changing domain, you can use the wildcard
character (*) to ensure that your requests are not blocked. For example:
<access origin="*"/>
Note: The wildcard character (*) cannot be used for data accessed by XMLHttpRequest. To access data
using the XMLHttpRequest, you must explicitly specify each domain.
When you use the wildcard character (*), webpages that your app accesses cannot access any of the app APIs.
In the example above, all requests that do not access content via XHR and that do not require access to app
APIs are allowed.
If your app is designed to access the device file system, you can define the file:/// scheme as the origin domain
to ensure that your requests are not blocked.
Here's how you can ensure that your file system requests are permitted:
1. On the Start menu, click BlackBerry >BlackBerry WebWorks <version>. A new browser window opens,
displaying the BlackBerry 10 WebWorks SDK tool.
2. Navigate to your project and click Config.
3. Locate the Access List section near the bottom of the list of preferences.
4. In the Origin field, enter the domain you want to allow your app to access. If your app is designed to access
data from an unknown or changing domain, you can use the wildcard character (*) to ensure that your
requests are not blocked.
5. To allow access to all subdomains within the specified domain, select Allow subdomains.
6. Click Add Access.
You can specify access to a domain by adding an <access> element to the config.xml file. The config.xml file
can contain multiple <access> elements to specify access to different domains. The <access> element is a
child of the top-level <widget> element
Adding Features 48
To add an access permission to the config.xml file:
In some cases, a permission is required only for a subset of the APIs contained by a plugin. In these cases, the
tools do not add the permission. If you intend to use the restricted APIs within the plugin, you must add the
required permission yourself. In addition, you may be required to add app permissions to use some HTML5
APIs, such as HTML5 notifications.
For example, adding the org.apache.cordova.file plugin to your project without specifying any permissions
allows you to access only those files within the application sandbox. However, to access other files on the
device file system, such as a music file, you must add the access_shared permission. In this case, adding the
plugin does not automatically add the permission. Instead, you must add the permission yourself, either using
the BlackBerry 10 WebWorks SDK web tool, or by manually adding them to the config.xml file.
To add plugin permissions using the BlackBerry 10 WebWorks SDK web tool:
1. On the Start menu, click BlackBerry >BlackBerry WebWorks <version>. A new browser window opens,
displaying the BlackBerry 10 WebWorks SDK web tool.
2. Navigate to your project and click Config.
3. In the Permissions section at the bottom of the page, select the permission you want to add to the project
from the Permit drop-down list then click Add Permission. For information about the available app
permissions, see Available app permissions.
The project's root folder contains the config.xml file, which contains the app permissions for the project. You
can add a directly to the config.xml file by adding a <rim:permit> element. The config.xml file can contain
one or more <rim:permit> elements, all of which must be children of the <rim:permissions> element.
Adding Features 49
2. Locate the <rim:permissions> element. If no <rim:permissions> element exists, add one:
<rim:permissions>
</rim:permissions>
3. Add the app permission by inserting a <rim:permit> element in the <rim:permissions> element.
For example, if you want to access a music file on the device file system, you must add the
access_shared permission to the file, as follows:
<rim:permissions>
<rim:permit>access_shared</rim:permit>
</rim:permissions>
For information about the available app permissions, see Available app permissions.
The following table identifies the available WebWorks app permissions, which are required to access specific
native functionality or capabilities. Typically the tools automatically add the required permission when the
plugin is added. However, if the plugin can function without the permission, and requires a permission only to
access certain APIs within the plugin, then the tools do not add the permission. If you intend to use the
restricted APIs, you must add the permission yourself.
Note: This list of permissions represents only those app permissions that may be required to use the
WebWorks or Cordova plugins that are installed with the BlackBerry 10 WebWorks SDK. Custom plugins that
access native functionality may require app permissions that are not listed here. For example, to use a custom
plugin that accesses the device's microphone to record audio, you must add the record_audio permission. For
a complete list of native app permissions, see App permissions in the BlackBerry 10 Native SDK
documentation.
Adding Features 50
Functionality or Permission value Description
capability
Email and PIN access_pimdomain_messages Allows the app to access email and
messages PIN messages, including viewing,
creating, sending, and deleting
messages.
Adding Features 51
Functionality or Permission value Description
capability
Contacts access_pimdomain_contacts Allows the app to access contacts,
including viewing, creating, and
deleting contacts.
However, you may need to modify the config.xml manually to add certain configuration information.
Specifically, you may need to add some <permit> elements to allow your app access to some functionality. If
you want to allow other apps to invoke your app, you also need to manually add the <invoke-target>
element and its children to define the invocation behaviour of your app.
Note: Although multiple copies of the config.xml file may exist within your project subfolders, you should edit
only the master copy. The master copy of the file is located in your project's root folder. Other versions of the
file are overwritten by the tools when a project is built, and any modifications made to those files are lost.
For a list of all the elements that you can use in a configuration document, see Elements in config.xml.
If you edit the master config.xml file, you may notice entries that are not listed in the BlackBerry
documentation. You can ignore these entries, as they are used by other platforms. During the build process,
the SDK tools strip out any entries that are unnecessary or invalid for the BlackBerry platform before packaging
the app resources in a .bar file.
Adding Features 52
<author href="http://www.example.com/"
rim:copyright="Copyright 1998-2012 My Corp">My Corp</
author>
<name>Sample application</name>
<description>
A sample application to demonstrate some features.
</description>
<rim:permissions>
<rim:permit>access_shared</rim:permit>
<rim:permit>access_location_services</rim:permit>
<rim:permit>use_camera</rim:permit>
</rim:permissions>
<icon src="icons/icon-150.png"/>
<rim:splash src="splash-1280x768.png"/>
<rim:splash src="splash-768x1280.png"/>
<content src="index.html"/>
<license href="http://www.example.com/"/>
</widget>
Elements in config.xml
The following table describes each element that can be used in the configuration document. It also specifies
how many times you can use each element in your config.xml file for a particular platform. A dash indicates
that the element is ignored for the specified platform.
Element Description
<access> Specifies that a BlackBerry WebWorks app can zero or more
access external network resources.
<author> Specifies the author's name. one
<content> Specifies the application start page. one
Adding Features 53
Element Description
<description> Specifies a human-readable description of the zero or more
application.
<icon> Specifies an icon that represents the application on zero or more
the Home screen of the BlackBerry device.
<license> Specifies end user license and copyright zero or one
information.
<name> Specifies a human-readable name for the one or more
application.
<preference> Defines a preference for the blackberry.app zero or more
plugin (for example, screen orientation).
<rim:invoke-target> Registers your application as a handler for an zero or more
invocation event.
<rim:permissions> Provides a container for <rim:permit> to specify one
application permissions for device features.
<rim:permit> Defines application permissions for device features. one or more
Must be child of <rim:permissions>.
<rim:splash> Specifies the image to display on the screen while zero or more
your application loads.
<widget> Provides a container for all other elements. one
widget element
Syntax
<widget xmlns="http://www.w3.org/ns/widgets"
xmlns:rim="http://www.blackberry.com/ns/widgets"
version="string"
id="string"
xml:lang="string"
rim:header="string"
rim:userAgent="string">
</widget>
Description
The <widget> element provides a container for all other elements, and it's the root element in the
configuration document for a BlackBerry WebWorks application.
Adding Features 54
Parent elements
None
Child elements
Many. For a list of elements, see the Elements in config.xml table.
Occurrences
One, at the root of the configuration document.
Attributes
You can use the following attributes in the <widget> element:
Attribute Description
• x.x.x
• x.x.x.x
Adding Features 55
Attribute Description
rim:userAgent Specifies the value for the user agent. The value that
you specify is sent as the value of the User-Agent
header, which is included with every HTTP request.
You can use this string to identify requests coming
from your app. The attribute value can be any string.
Example
<widget xmlns="http://www.w3.org/ns/widgets"
xmlns:rim="http://www.blackberry.com/ns/widgets"
version="2.0.0.0"
Adding Features 56
id="sampleapp"
rim:header="RIM-Widget:rim/widget"
rim:userAgent="BlackBerry10/MyWebWorksApp">
</widget>
access element
Syntax
Description
The <access> element specifies that a BlackBerry WebWorks app can access external network resources. By
default, if you do not specify an <access> element, an app only has access to local resources, which includes
all resources packaged in the apps .bar file.
If you specify more than one <access> element, the most specific definition is used. For example, if you use
http://somedomain.com and http://specific.somedomain.com, the <access> element that
uses the first definition (and any features defined under it) is ignored.
As a best practice, you should protect your communication channel by using HTTPS when you expose
sensitive APIs to the domain. For information about best practices on securing your app, see Accessing
external resources.
Parent elements
<widget>
Child elements
None
Occurrences
Zero or more
Attributes
You can use the following attributes in the <access> element:
Attribute Description
origin
The origin attribute defines the web address for the access request.
Adding Features 57
Attribute Description
You can specify a wildcard (*) for the origin attribute to whitelist any
domain, but only for domains that do not access content through
XMLHttpRequest. If the domain accesses data through
XMLHttpRequest, you must explicitly specify the domain for the
origin attribute.
uri The uri attribute defines the web address for the access request. This
attribute is only supported for backwards compatability. Going forward,
you should use the origin attribute.
subdomains
The subdomains attribute is a Boolean value that specifies whether
the host component in the access request applies to subdomains of the
domain that is specified in the origin attribute.
author element
Syntax
<author href="string"
rim:copyright="string"
email="string"
rim:copyright="string"
xml:lang="string">
string</author>
Description
The <author> element specifies information about the people or organizations that are involved with the
creation of a BlackBerry WebWorks application.
Adding Features 58
For BlackBerry smartphone applications running BlackBerry 7 or earlier, author information appears in the
Vendor property when BlackBerry device users view the list of applications that are installed on the
BlackBerry device.
You can access this element by using the blackberry.app.author property that is provided in the
BlackBerry WebWorks API.
Parent elements
<widget>
Child elements
none
Occurrences
One
Attributes
You can use the following attributes:
Attribute Description
href The href attribute specifies a web address that is associated with the
author (for example, the web page of the author).
Adding Features 59
Attribute Description
email The email attribute specifies the email address that is associated with
the author.
xml:lang The xml:lang attribute specifies the language that is used in the
element. For more information about this attribute, visit www.w3.org.
its:dir The its:dir attribute specifies the directionality of the language. For
example, its:dir="rtl" specifies a language that is written from
right to left. For more information about this attribute, visit www.w3.org.
Example
<author href="http://www.example.com/"
rim:copyright="Copyright 1998-2012 My Corp">My Corp</author>
content element
Syntax
<content src="string"
rim:allowInvokeParams=["true" | "false"]
type="string"
charset="string" />
Description
The <content> element specifies the start page that the BlackBerry WebWorks application displays when it
runs. The start page can contain the web address of a file that is located outside of the application archive.
Adding Features 60
Parent elements
<widget>
Child elements
None
Occurrences
One
Attributes
You can use the following attributes:
Attribute Description
src
The src attribute specifies the source HTML file in
the application archive.
rim:allowInvokePar
The rim:allowInvokeParams attribute specifies
ams
that parameters can be passed to your application
when it is invoked from another application.
type
The type attribute specifies the MIME type of the file
that is specified in the src attribute.
charset
The charset attribute specifies the character set
that is used by the file that is specified in the src
attribute.
Adding Features 61
Examples: Specifying a start page
description element
Syntax
<description>string</description>
Description
The <description> element specifies a human-readable description for a BlackBerry WebWorks
application.
You can access this element by using the blackberry.app.description property that is provided in the
BlackBerry WebWorks API.
Parent elements
<widget>
Child elements
None
Occurrences
One
Attributes
You can use the following attributes in this element:
Attribute Description
xml:lang
The xml:lang attribute specifies the language that is used in the
element. For more information about this attribute, visit www.w3.org.
its:dir
The its:dir attribute specifies the directionality of the language. For
example, its:dir="rtl" specifies a language that is written from
right to left. For more information about this attribute, visit www.w3.org.
Adding Features 62
Attribute Description
Example
<description>
This application displays "Hello World" on the screen.
</description>
icon element
Syntax
Description
The <icon> element specifies a custom icon for a BlackBerry WebWorks application. The icon that you
specify in the src attribute is the application's icon that appears on the Home screen of the BlackBerry
device. The icon must meet the requirements for custom or default icons.
Parent elements
<widget>
Child elements
None
Occurrences
Zero or more
Attributes
You can use the following attributes in this element:
Adding Features 63
Attribute Description
src
Specifies the path for an image file in the application
archive.
rim:hover
A Boolean value that specifies whether the icon is
used as a hover icon. The first hover icon in the
configuration document is used as the hover icon for
the application.
BlackBerry 10 icons
Your icon image should be 24-bit PNG format with an alpha channel. For information about designing icons for
BlackBerry 10, see the UI Guidelines.
If you do not specify an icon for your BlackBerry 10 application, the BlackBerry WebWorks Packager uses the
default application icon.
• Named the same as the non-localized image file name that you specified in the <icon> element.
• Stored in the appropriate locale subfolder that corresponds with the localized language.
When you use localized images, the files must be stored in individual locale folders (for example, "/locales/en-
US", "/locales/fr") which are direct descendants of the root locales folder. The locales folder must be
located in the root of your application folder so that the BlackBerry WebWorks Packager can build your
application. The locale strings specified in the folder name must use the naming conventions that are specified
in the Internet Engineering Task Force (IEFT) Best Current Practice (BCP) 47 specification. For example, you
Adding Features 64
can use the Language-Region naming convention as in the following examples: en-US (United States English),
de-DE (German for Germany), and fr-CA (Canadian French).
The file names for the localized images must be named exactly as the non-localized image files that you
specified in the icon element. You can store the non-localized images in subfolders but the locale folder must
use the same subfolder structure for the localized images. When the BlackBerry 10 OS is set to one of the
locales (for example, German or French) and localized images are present for that locale, the BlackBerry 10
OS selects the images from the respective locale subfolder. If no localized images are available for the
specified locale, the BlackBerry 10 OS selects the non-localized icon image located in the root.
In this example, if the French locale is set on the device, even if the optimum icon resolution is 150x150, the
BlackBerry 10 OS uses the locales/fr/icon-86.png file because it's the only icon image available for
this locale.
locales/de/icon-86.png
locales/de/icon-150.png
locales/fr/icon-86.png
icon-86.png
icon-150.png
license element
Syntax
<license>string</license>
Description
The <license> element specifies the end user license agreement or a copyright statement for a BlackBerry
WebWorks application. This element is optional. If you specify this element, you can implement a feature to
prompt BlackBerry device users to accept or decline the license agreement when they run the application for
the first time. After users agree to the license agreement, the prompt does not appear when they run the
application again.
The contents of the license agreement are also available on the About screen in the application.
Parent elements
<widget>
Adding Features 65
Child elements
None
Occurrences
Zero or one
Attributes
You can specify the following attributes for this element:
Attribute Description
xml:lang
The xml:lang attribute specifies the language that is used in the
element. For more information about this attribute, visit www.w3.org.
its:dir
The its:dir attribute specifies the directionality of the language. For
example, its:dir="rtl" specifies a language that is written from
right to left. For more information about this attribute, visit www.w3.org.
href
The href attribute specifies a web address for a web page that contains
content or license information.
Example
<license>
Example license
Copyright © 2012 My Corp.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS
BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, INSULT OR OTHERWISE, ARISING FROM, OUT OF OR
IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
Adding Features 66
SOFTWARE.
</license>
name element
Syntax
<name>string</name>
Description
The <name> element specifies a human-readable name for a BlackBerry WebWorks application that you can
use, for example, in an application menu.
If you do not specify a name element, the application is not valid. For BlackBerry 10 applications, the name
must be 25 characters or less.
You can also specify a name by using the blackberry.app.name property that is provided in the
BlackBerry WebWorks API.
Parent elements
<widget>
Child elements
None
Occurrences
One
Attributes
You can use the following attributes in this element:
Attribute Description
xml:lang
The xml:lang attribute specifies the language that is used in the
element. For more information about this attribute, visit www.w3.org.
Adding Features 67
Attribute Description
its:dir
The its:dir attribute specifies the directionality of the language. For
example, its:dir="rtl" specifies a language that is written from
right to left. For more information about this attribute, visit www.w3.org.
You can use this attribute for localization.
Example
preference element
Syntax
Description
The <preference> element defines a preference for the blackberry.app plugin (for example, screen
orientation).
Parent elements
<widget>
Child elements
None
Occurrences
Zero or more
Features
To specify a particular feature for your application, use the following associated attributes. In all cases, the
name value is case insensitive.
Adding Features 68
Preference Description
orientation
Specifies the orientation for screens in your app.
Example
AutoHideSplash
Hides the splash screen for your application. The value can be "true" or "false",
Screen
with "true" being the default. When false, the splash screen is displayed until
splashscreen.hide() is invoked.
Example
backgroundColo
Specifies the background color for your application. The value must specify a color
r
value in the ARGB pixel format using 8 hexadecimal digits.
Example
childBrowser
Disables child browser windows. By default, when the content tries to open a resource
in a new window or tab (by using window.open(), or by specifying _blank as the
target of an anchor), the WebWorks app opens a secondary browser window to display
the resource. This feature is enabled by default.
The value must specify a value of "disable".
Adding Features 69
Preference Description
Example
DiskCache
Enables WebView caching, which prevents the app from issuing multiple network
requests for the same resource.
Example
HideKeyboardFo
When enabled, hides the row of buttons (Previous, Next, and Submit) that is displayed
rmAccessoryBar
by default when an <input> element on the current page of the app gets focus.
Example
<preference name="HideKeyboardFormAccessoryBar"
value="enable" />
popupBlocker
Enables the popup blocker, which prevents your app from displaying popups. By
default, WebWorks apps display popups in a child browser window.
Example
websecurity
Disables web security. Disabling web security allows you to access remote content
from unknown sources. Before packaging your app for distribution, you should remove
this setting unless it is explicitly required.
Adding Features 70
Preference Description
Example
rim:invoke-target element
Syntax
<rim:invoke-target id="string">
<type>[ APPLICATION | VIEWER ]</type>
<filter>
<action>string</action>
<mime-type>mime type</mime-type>
<property var=["exts" | "uris"] value="string" />
</filter>
</rim:invoke-target>
Description
You can use the <rim:invoke-target> element to register your BlackBerry WebWorks application as a
handler for invocation events. In BlackBerry 10 OS, the invocation framework provides the ability by which a
client process can send a message to a target process so it can perform a certain action.
If you register your application with the invocation framework, your application can be invoked through:
All invocations must specify an action that the target must perform as well as data to be acted upon. The data
can be specified by using a combination of MIME types, URIs, and file extensions.
Note:
You must include the following namespace declaration in the parent <widget> element to use the
<rim:invoke-target> element:
xmlns:rim="http://www.blackberry.com/ns/widgets">
Parent elements
<widget>
Adding Features 71
Child elements
See element structure below.
Occurrences
Zero or more
Element structure
All child elements of the rim:invoke-target element have the rim: namespace prefix by default.
Therefore, you do not have to prepend any of the other child elements of the rim:invoke-target element
with rim:.
rim:type rim:invoke-target
Describes the type of invocation of
rim:target. The type can be one of the
following:
• application
• viewer
rim:require-source- rim:invoke-target
Lists the capabilities that the invoking
permissions
application must support.
rim:filter rim:invoke-target
Describes a set of instances in which the target
may receive an unbound invocation.
rim:action rim:filter
Contains a valid action for the target to perform
on the data.
Adding Features 72
Element Parent Description
rim:mime-type rim:filter
Contains a valid MIME type for the data
(wildcard characters are allowed).
rim:property rim:filter
Contains a valid prefix for URIs or suffix for file
extensions of the URI provided during
invocation.
Element attributes
Example:
com.ea.needforspeed.targ
et
rim:var rim:property
Specifies extra properties that can
be used to register an unbound
invocation. The invocation
framework supports invocation by
URI or by file extensions. The value
can be uris or exts.
rim:value rim:property
Specifies the property values to use
when registering an unbound
Adding Features 73
Attribute Defined in Description
• http://
• https://
• ftp://
• html
• htm
• php
• jsp
• asp
Examples
<widget xmlns:rim="http://www.blackberry.com/ns/widgets">
.
.
.
<rim:invoke-target id="com.domain.subdomain.appname.app">
<type>APPLICATION</type>
<filter>
<action>bb.action.OPEN</action>
<action>bb.action.SET</action>
<mime-type>text/*</mime-type>
<property var="exts" value="bmp,css,html,js" />
<property var="uris" value="data://local,file://" />
</filter>
</rim:invoke-target>
</widget>
<widget xmlns:rim="http://www.blackberry.com/ns/widgets">
.
.
.
Adding Features 74
<rim:invoke-target id="com.domain.subdomain.appname.app">
<type>APPLICATION</type>
<filter>
<action>bb.action.OPEN</action>
<mime-type>application/*</mime-type>
<mime-type>text/*</mime-type>
<mime-type>audio/*</mime-type>
<mime-type>image/*</mime-type>
<mime-type>message/*</mime-type>
<mime-type>video/*</mime-type>
</filter>
<filter>
<action>bb.action.VIEW</action>
<mime-type>text/*</mime-type>
</filter>
<filter>
<action>bb.action.SET</action>
<mime-type>image/*</mime-type>
<property var="exts" value="bmp,png,jpg,gif" />
</filter>
</rim:invoke-target>
</widget>
<widget xmlns:rim="http://www.blackberry.com/ns/widgets">
.
.
.
<rim:invoke-target id="com.domain.subdomain.appname.app">
<type>APPLICATION</type>
<filter>
<action>bb.action.OPEN</action>
<mime-type>image/*</mime-type>
<mime-type>text/*</mime-type>
<mime-type>video/*</mime-type>
</filter>
</rim:invoke-target>
<rim:invoke-target id="com.domain.subdomain.appname.view">
<type>VIEWER</type>
<filter>
<action>bb.action.VIEW</action>
<mime-type>image/*</mime-type>
<mime-type>text/*</mime-type>
<mime-type>video/*</mime-type>
</filter>
</rim:invoke-target>
</widget>
Adding Features 75
Code sample: Parsing invoke parameters
When you set the <content> element's rim:allowInvokeParams attribute to a value of true, the start
up parameters for the application are available to the start page as a query string. You can parse the query
string using JavaScript.
function parseQueryString() {
return queryParamResult;
}
rim:permissions element
Syntax
<rim:permissions>
<rim:permit> ...</rim:permit>
</rim:permissions>
Description
The <rim:permissions> element is a container element for the <rim:permit> element, which specifies
the permissions for various features in a BlackBerry WebWorks application.
See the <rim:permit> element for information about permission features.
Adding Features 76
Note:
You must include the following namespace declaration in the parent <widget> element to use the
<rim:permissions> element:
xmlns:rim="http://www.blackberry.com/ns/widgets">
Parent elements
<widget>
Child elements
<rim:permit>
Occurrences
One
The following sample demonstrates how to set the permissions for reading and writing files, reading
GPS location information, and accessing camera data.
<widget xmlns:rim="http://www.blackberry.com/ns/widgets">
.
.
.
<rim:permissions>
<rim:permit>access_shared</rim:permit>
<rim:permit>read_geolocation</rim:permit>
<rim:permit>use_camera</rim:permit>
</rim:permissions>
<widget>
rim:permit element
Syntax
<rim:permissions>
<rim:permit>permission string</rim:permit>
</rim:permissions>
Description
The <rim:permit> element specifies permission access to various features in a BlackBerry WebWorks
application (for example, accessing the GPS location or the camera).
Note:
Adding Features 77
You must include the following namespace declaration in the top-level <widget> element to use the
<rim:permit> element:
xmlns:rim="http://www.blackberry.com/ns/widgets">
Parent elements
<rim:permissions>
Child elements
None
Occurrences
One or more
Attributes
You can specify the following attributes:
Attribute Description
system The system attribute indicates that the specified permission is a
system permission. Set system="true" to indicate a system
permission.
Permissions
The following table identifies the available permissions for WebWorks plugins, which are required to access
specific native functionality or capabilities.
Note: This list of permissions represents only those permissions that may be required when adding the
WebWorks or Cordova plugins that are installed with the BlackBerry 10 WebWorks SDK. Custom plugins may
require permissions that are not listed here. For example, to use a custom plugin that accesses the device's
microphone to record audio, you must add the record_audio permission. For a complete list of native app
permissions, see App permissions in the BlackBerry 10 Native SDK documentation.
Adding Features 78
Functionality or Permission value Description
Capabilities
Camera use_camera Allows this app to take pictures,
record video, and use the camera's
flash.
Adding Features 79
Functionality or Permission value Description
Capabilities
BBM Social Platform bbm_connect Allows this app to connect to BBM so
that the user can chat or update their
BBM profile without leaving the BBM
connected app.
Email and PIN access_pimdomain_messages Allows this app to access email and
messages PIN messages, including viewing,
creating, sending, and deleting
messages.
The following example demonstrates how to set the permissions for reading and writing files,
recording audio, accessing camera data, and push.
<widget xmlns:rim="http://www.blackberry.com/ns/widgets">
.
.
.
<rim:permissions>
<rim:permit>access_shared</rim:permit>
<rim:permit>record_audio</rim:permit>
<rim:permit>use_camera</rim:permit>
<rim:permit system="true">_sys_use_consumer_push</rim:permit>
</rim:permissions>
<widget>
Adding Features 80
rim:splash element
Syntax
Description
The <rim:splash> element specifies the image to display on the screen while the BlackBerry 10 device
loads your application. This element is optional.
To target multiple screen sizes of BlackBerry 10, you can specify image files with different resolutions. At
runtime, the BlackBerry 10 OS selects the appropriate image to display. Your splash screen image should fit
the entire screen size so that it fills the screen. For information about BlackBerry 10 screen sizes, see the
BlackBerry UI Guidelines.
The image for your splash screen can be any of the following file formats: .png, .jpg, .jpeg, .gif, or .bmp.
Note:
You must include the following namespace declaration in the parent <widget> element to use the
<rim:splash> element:
xmlns:rim="http://www.blackberry.com/ns/widgets">
Parent elements
<widget>
Child elements
None
Occurrences
Specify 0 or more <feature> elements withina <widget> element.
<widget xmlns:rim="http://www.blackberry.com/ns/widgets">
.
.
.
<rim:splash src="splash-1024x600.png" />
<rim:splash src="splash-600x1024.png" />
<rim:splash src="splash-1280x768.png" />
<rim:splash src="splash-768x1280.png" />
<widget>
Adding Features 81
Using localized splash images
To use localized image files for the splash screen, the image files must be :
• Named the same as the non-localized image file that you specified in the <rim:splash> element.
• Stored in the appropriate locale subfolder that corresponds with the localized language.
When you use localized images, the files must be stored in individual locale folders (for example, "/locales/en-
US", "/locales/fr") which are direct descendants of the root locales folder. The locales folder must be
located in the root of your application folder so that the BlackBerry WebWorks Packager can build your
application. The locale strings specified in the folder name must use the naming conventions that are specified
in the Internet Engineering Task Force (IEFT) Best Current Practice (BCP) 47 specification. For example, you
can use the Language-Region naming convention as in the following examples: en-US (United States English),
de-DE (German for Germany), and fr-CA (Canadian French).
The file names for the localized images must be named exactly as the non-localized image files that you
specified in the <rim:splash> element. You can store the non-localized images in subfolders but the locale
folder must use the same subfolder structure for the localized images. When the BlackBerry 10 OS is set to one
of the locales (for example, German or French) and localized images are present for that locale, the BlackBerry
10 OS selects the images from the respective locale subfolder. If no localized images are available for the
specified locale, the BlackBerry 10 OS selects the non-localized icon image located in the root.
In this example, if the French locale is specified on the device, even if the optimum resolution is
1024x600, the BlackBerry 10 OS uses the locales/fr/splash-1280x768.png file because it's
the only landscape image available for this locale.
locales/de/splash-1024x600.png
locales/de/splash-600x1024.png
locales/de/splash-1280x768.png
locales/de/splash-768x1280.png
locales/fr/splash-1280x768.png
locales/fr/splash-768x1280.png
splash-1024x600.png
splash-600x1024.png
splash-1280x768.png
splash-768x1280.png
App integration
The BlackBerry 10 OS provides the invocation framework to bring a powerful cross-application integration
capability to the platform. You can use the invocation framework and cards to greatly enhance the user
experience and functionality of your app.
Adding Features 82
The invocation framework facilitates inter-app communication. The framework provides the capability for your
application to launch another application from within your app's UI. This capability provides for better
multitasking and a smooth application flow, and allows the BlackBerry device user to continue with a task
without losing focus. You can also integrate your application with core applications. For example, email, file
manager, pictures, music, and BBM can be integrated and called by your application when needed.
Cards enhance the invocation framework's capabilities. Cards allow you to launch a particular screen of
another application in the form of a card, instead of launching the full application. Cards also use fewer system
resources and offer a great user experience.
Related resources
Invocation framework
The invocation framework in BlackBerry 10 OS allows one application to invoke another by sending it a
message. When an application calls for an invocation on some content, the invocation framework responds
with appropriate applications that can carry out a requested action on that particular content. For example,
using the invocation framework for your app can allow the BlackBerry device user to perform a set of actions
on a piece of content such as a .doc file. These actions will allow the user to share, open, or send the .doc file in
an email using another application from within the UI of your app. In this example, your application is the client
application in the invocation framework and the application that shares, opens, or sends the .doc file as an
email is the target application.
Depending on your application's functionality, the invocation framework can allow your application to become
more discoverable if you register your app as a target application. This allows other applications to invoke your
application without first knowing about your application.
An invocation request is the message structure that is passed between a client application and a target
application. An invocation message represents either a request for the target to perform a task, or a
notification about an event that has occurred. An invocation request is passed to a target application when the
target is invoked. The framework takes care of launching the target application if it is not already running. An
invocation request contains:
Adding Features 83
• Target: The unique ID of the target application
• Action: The action that should be performed on the data
• Data: The data that should be acted upon
Invocation targets
An application that is registered with the invocation framework is called a target application. Other applications
can invoke a target application by using the invocation framework. Upon invocation, the user's context
switches to the target application.
The target ID in an invocation message tells the invocation framework where to send the invocation message. A
target ID is assigned by the target application developer and is guaranteed to be unique when the application
is signed. To help select a unique value, the target ID uses a reverse DNS style structure (for example,
com.acme.myapp).
Invocation action
The action attribute in an invocation request describes the task that can be performed on the content. Every
action is uniquely identified by a name. Action names end with a verb in uppercase letters. To help identify the
ownership and uniqueness of each action, the action attributes in an invocation request use a reverse DNS
style structure (for example, com.acme.action.VIEW).
The invocation framework supports a set of actions that define various tasks which your application can
request the platform to perform (for example, viewing an image). You can also use actions to register your app
as a target in the core applications of the BlackBerry 10 OS (for example, registering your app as a target would
allow an image in the Pictures app to be shared with your app).
All the actions available on the BlackBerry 10 OS begin with bb.action and are appended by a verb in
uppercase letters. Before you add a custom action, check to see if there is already a suitable action provided
by the platform. For a complete list of available platform actions, see Invoking core applications.
Invocation data
The data in an invocation message is provided as a URI and a MIME type. The URI identifies the location of the
data resource and the MIME type describes the data. For common MIME types, the platform can deduce the
MIME type from the URI, even if you do not specify the MIME type when you specify a URI. For example, it can
deduce the MIME type from a file extension in the URI.
For small amounts of data, you can include the data directly in the invocation message using the data
attribute. The URI is assumed to be data://local and can therefore be left out of the message. When you
send data directly in the invocation message, you must provide a MIME type because the platform can only
deduce the MIME type if a URI is present in the message. The total size of the message cannot exceed 16 KB.
A custom MIME type that describes data should begin with the application/vnd. prefix. It should be
followed by sufficient context so that the MIME type is properly distinguished from other types. If the data has
multiple encodings represented in the MIME type, make sure that the data is the last element defined in the
type (for example, application/vnd.mycompany.mydata).
You can also specify additional, optional data by using the metadata attribute in an invocation message. Data
is sent in the JSON format.
Adding Features 84
Sending invocation
Bound invocation
The following image show how a client application can use the bound invocation to invoke a target application
of its choice. In this case, App 2 opens the document contained in the client application.
Before you can send an invocation request, you must add the com.blackberry.invoke plugin to your app.
To add the plugin, on the command line, navigate to your project folder and run the following command:
blackberry.invoke.invoke({
target: "com.example.image.view ",
action: "bb.action.OPEN",
type: "image/png",
uri: "file:///path/to/image.png"
}, onSuccess, onError);
Once the invocation request is sent, the invocation response is handled by the invocation framework itself.
However, you must create JavaScript functions to handle the success or error events. Here's a sample that
shows you how to do that:
function onSuccess() {
console.log("<p>Invocation successful</p>");
}
function onError(error) {
console.log("<p>Invocation error: " + error + "</p>");
}
Target discovery
After learning about how to send an invocation, you must be wondering how you can determine what targets
are available on the device. This section deals with exactly that. You can hard code the target application that
you want to send an invocation message to, or you can query the invocation framework to find out what targets
are installed on the BlackBerry device. The invocation framework uses a target filter to allow the target
applications to declare the types of invocation they support. When a client application queries the invocation
framework, the framework uses the target app's filter to describe the kind of target it is looking for and the data
it has to offer.
The quality of the results is generally dependent on how specific the target query request is. A target query
request should consist of the URI and the MIME type. If the MIME type is left out, the framework tries to
determine the type using the URI.
Adding Features 85
A client application can include the action, to be performed on the data, in its target query request. If the
action is not specified in the target query request, the query result will contain a list of all the actions that can
be performed on the specified data by the available targets.
The invocation framework returns a query result which includes the targets grouped by the action that these
targets support. For each target, the query result provides the target ID, the target type (an application or a
card), and other information about the target, such as icons and labels, that can be used to display the target
in the client application's screen.
To determine what targets are suitable candidates, the invocation framework applies a set of brokering rules.
For more information, see Target selection and brokering process.
The following code demonstrates a target query request in which a client application searches for targets that
support the bb.action.OPEN action on image/png images, which are sent as a file:// URI.
var request = {
"action": "bb.action.OPEN",
"type": "image/png",
"uri": "file://path/to/image.png",
"target_type": ["APPLICATION", "VIEWER"],
"action_type": "ALL"
};
function onSuccess(response) {
console.log("<p>Invocation query response: " + response + "</p>");
var data = JSON.stringify(response);
//can now parse the data variable for invocation targets
// that matched the query criteria
}
function onError(error) {
console.log("<p>Invocation query error: " + error + "</p>");
}
Unbound invocation
In this section, you will learn how the invocation framework can make invoking a target application easy, by
removing the need to query. Instead of sending a target query request to determine the available targets, the
client application can simply send an invocation request to the framework without specifying a target. This kind
of invocation is called unbound invocation. If you send an unbound invocation, the framework searches for and
invokes a suitable target application for you.
The following image shows how a client application (App 1) lets the invocation framework return the most
suitable target app for a particular action. In this case, App 2 is the most suitable application to open the
document contained in the client application.
Adding Features 86
To find the best candidate, the framework first uses a brokering process. It applies a set of rules to determine
which target applications support the client application's invocation request. If there is more than one suitable
target available, the framework applies a set of selection rules to choose the most appropriate target. For more
information, see Target selection and brokering.
You can also send an invocation request without specifying an action item, since only the data is sent. The
framework determines the type of target and the action to be performed.
If you don't define the action parameter, the invocation framework tries to find an appropriate target
application for the bb.action.VIEW action. If no suitable target application is found for
bb.action.VIEW, the invocation framework falls back to determine an appropriate target application that
supports bb.action.OPEN. If still no suitable target application is available for bb.action.OPEN, the
invoke request is unsuccessful.
The following sample code shows how you can easily create an unbound invocation. The sample code invokes
the most suitable target application to handle the image.png file, specified by the URI.
blackberry.invoke.invoke({
uri: "file:///path/to/image.png"
}, onSuccess, onError);
Data transfer
This section explains how the invocation framework sends data, to help you understand how to optimize your
invocation requests, and send multiple files between client and target applications. An invocation request
describes the data that can be acted upon by the target application.
Although applications can use many different URI schemes to transfer data, the invocation framework
provides support for in-band transfer and file transfer.
In-band transfer
Most often, an invocation request carries only a small amount of data (less than 16 KB). In some cases this
small amount of data can be encoded directly into a URI. It is also possible to send it as part of the invocation
request. When data is sent as part of the invocation message, it is placed in the data attribute. During an in-
band transfer, the URI value should be set to data://local which points to the data attribute. When the
data is sent in-band, the MIME type must describe the type of the data, to allow both the invocation framework
and the target application to handle the message.
blackberry.invoke.invoke({
target: "com.example.image.view ",
action: "bb.action.OPEN",
type: "text/plain",
data: "Hello World!",
}, onSuccess, onError);
Adding Features 87
File handling
This section contains information on how invocation framework handles file transfers and the type of files
supported.
File extensions
The invocation framework supports file handling based on the file extension. The file extensions can be defined
as file:// within the scheme parameter when the data is referenced by the URI. The invocation framework
also supports the declaration of the exts attribute within the target filters. If in an invocation request, the URI
is suffixed with a file extension that matches any of the file extensions declared in the exts attribute, then a
given target filter will match with that invocation request. When the exts attribute is defined, the target filter
implicitly supports the uris="file://" for those declared extension cases.
The exts attribute is only applied if the accompanying uris contain a file:// based uri. Also, combining
exts and specific MIME types in a target filter means that both must be specified by a client application for
the target filter to successfully match with an invocation request. The best practice in most cases is to define
the exts related target filters as a separate declaration, where uris is file:// and the MIME type is a
wildcard character (*).
File transfer
Sending an invocation request with a file:// URI to pass files succeeds only if the target application can
access the file. The platform supports the use of a shared area in the file system to share data between the
client and target applications. However, to send sensitive data to a target application, a client application can
use the invocation framework's file transfer handling feature. When the framework receives an invocation
request with a file:// URI, it inspects the URI to determine if the request refers to a shared area. If the file is
already shared, the invocation request passes the URI to the file in the shared area, as specified by the sender.
However, if the invocation framework detects that the file is not shared, then by default it creates a read/write
copy of the file in a private inbox for the target application. The client application can specify the file transfer
mode attribute to override this behavior. Invocation requests support the following modes:
Adding Features 88
File transfer mode Description
read/write permissions then the sender must be the
owner of the file.
For certain invocation requests, you might want to send multiple files in a single request. The invocation
framework supports a special set of MIME types (type/subtype). Each type is a combination of supported file
types, as explained below:
When sending multiple files, you can set the URI attribute to describe the common file path that is associated
with each file. Usually, this file path is the common root directory, if one exists. If no common root directory
exists, set the uri to file://. After you set the type and URI, you can assign the list of individual file URIs to
the data section using the following JSON format:
[
{
'uri':<file-uri>,
'type':<mime-type>,
'data':<metadata>
}
]
Adding Features 89
Attribute Format Description Mandatory Example
uri file URI The URI of the file Yes file://
being listed. The path/to/file
URI prefix must
match the
invoke.uri
attribute value.
type MIME The MIME type of No image/jpeg
the specified file.
data JSON Additional JSON No test metadata
formatted
metadata.
Receiving invocation
You can configure your application to receive invocation request from other applications. To receive an
invocation request, your application must support invocation targets. To support invocation targets, you must
declare your targets in the config.xml file and handle invocation messages.
Target declaration
In order to be invoked, an application identifies itself by declaring itself as a target in its config.xml file. To
declare a target, add the following elements to the config.xml file for each target that the application exposes.
<invoke-target id="com.example.image.view">
<invoke-target-type>application</invoke-target-type>
<invoke-target-name>My App Name</invoke-target-name>
<icon>
<image>icon.png</image>
</icon>
</invoke-target>
To let the platform know the type of the target, define the <invoke-target-type> element as shown in
the example below.
Attribute Description
invoke- Uniquely
target id identifies the
application as a
target. This
Adding Features 90
Attribute Description
parameter can
also be used by
the client
applications to
perform Bound
invocation.
type The type of the
target.
Applications and
cards are
supported as
types of the
target.
name The name of the
target
application.
image The icon for the
target
application.
The following sections explain how you can create different kinds of targets. Targets include applications and
cards.
Receiving invocations
Declaring your application as a target is essential for receiving an invocation request, but to be invoked you
need to add code in your application to receive invocation messages. Before you can receive invocation
messages, you must specify your app in the config.xml file as shown below:
<rim:invoke-target id="com.bb.test.invokable">
<type>APPLICATION</type>
<filter>
<action>bb.action.OPEN</action>
<mime-type>text/plain</mime-type>
</filter>
</rim:invoke-target>
The following code describes how to configure your application to listen for invocation messages:
Adding Features 91
// The following function parses the incoming data
function onInvoked(invokeRequest) {
}
function onInvoked(info) {
if(info.source) {
console.log("Source: " + info.source);
}
if(info.target) {
console.log("Target(me): " + info.target);
}
if(info.action) {
console.log("Action: " + info.action);
}
if(info.data) {
console.log("Data: " + info.data);
//the data comes in as a base64 string you can convert it using
atob(...)
//note that atob will fail if you are being passed unicode strings
console.log("Data: " + atob(info.data));
}
}
document.addEventListener('invoked',onInvoked);
You can also specify any particular behavior that you'd like your app to exhibit when it is invoked (for example,
screen orientation) by setting app preferences. For more information, see Configuring your app preferences.
Target filters
One of the key features of the invocation framework is the ability to discover target applications or cards on a
BlackBerry device. Targets are discovered based on the filters they declare in their config.xml file, which
describe the kinds of invocation request that a target supports. Target filters allow your application to be
queried for by other apps and make your application a candidate for unbound invocation requests.
Target filters are declared as part of the <invoke-target> element in the config.xml file and consist of the
following attributes:
Adding Features 92
Attribute Description
filter Describes the
criteria for this
application to be
considered for
unbound
invocations or
invocation
queries.
action Describes the
actions that can
be performed on
the content. It
represents the
action that the
target supports
for the types
specified in the
type attribute.
Include one
<action>
element for each
supported
action.
mime-type Describes the
type of content.
This attribute
represents the
different types
for which the
specified actions
are supported.
The type and the
subtype can
both be
specified as a
wildcard, within
a target filter.
For example, a
filter can specify
image/png,
image/* or *.
Adding Features 93
Attribute Description
Include one
<mime-type>
element for each
supported MIME
type.
uris Describes the
supported URI
pattern that
must prefix the
URI that is
provided in the
invocation
request. This
attribute
represents the
URI prefixes that
describe how
the target
supports the
delivery of the
data. The URI
value may
contain the
single wildcard
character * to
indicate that the
filter
supports any del
ivery
mechanism. If
the target
application or a
card supports
the delivery of
the data as part
of the message
body then it
should include
the data://
local URI.
Adding Features 94
Attribute Description
exts Represents the
list of file
extensions
supported by the
target. The
values specified
in this attribute
apply only to
file:// URIs.
When exts are
specified in a
target filter, they
are generally
specified in
conjunction with
MIME type=*.
A best practice
is to be as
specific as
possible when
specifying the
filter criteria, to
increase the
chances of
being selected
to handle the
invocation
request.
Wildcard
characters (*)
are considered a
relatively weak
match when
performing
selection,
therefore if your
target supports a
specific set of
types, you must
specify each of
the types in the
filter. In cases
Adding Features 95
Attribute Description
where your
application
supports both
specific MIME
types and
extensions, you
should split the
registration into
two separate
filters. One filter
registers for the
specific types
and one filter
registers for the
extensions
against the
type=*.
When you declare a target filter, make sure that your filter description abides by the following rules:
• The URI value cannot be set as a wildcard character (*). That is, you cannot declare <property var=
"uris" value="*"/> in your config.xml file.
• If the target filter contains actions such as bb.action.VIEW or bb.action.OPEN, and has MIME types
set as a wildcard character (*), and has the URI attribute set as data:// or file:// or left unstated,
then your application cannot be deployed or installed on the device.
• For a target filter that utilizes the URI file:// and a MIME type wildcard character (*), to successfully
register with the invocation framework, you must also specify a file extension value which is not a wildcard
character (*).
• If you declare a file extension value in the target filter, the file extension value is considered during the
brokering and selection process if it is used with a file:// URI.
If your application uses a target filter declaration that is restricted, then on deployment, the
result::failure 884 Restricted Invoke Filter detected error is displayed in the command
line tool.
Here are some examples of target filters that successfully register with the invocation framework:
• actions=bb.action.OPEN;types=*;uris=http://;
• actions=bb.action.OPEN,bb.action.VIEW;types=*;uris=file://;exts=jpg,gif,tif
;
• actions=bb.action.VIEW;types=*;uris=data://;exts=jpg,gif,tif;
The following target filters do not follow the rules specified above and will not allow the application to be
deployed or installed on the device:
Adding Features 96
• actions=bb.action.OPEN,bb.action.VIEW,bb.action.SET;types=*;uris=file://;
• actions=bb.action.OPEN;types=*;uris=data://;
• actions=bb.action.VIEW;types=*;uris=*;
• actions=bb.action.VIEW;types=*;
• actions=bb.action.OPEN,bb.action.VIEW;types=*;uris=file://;exts=*;
The following example describes an invoke target that has two filters. The first filter describes the support for
bb.action.OPEN and bb.action.VIEW actions on .png and .jpeg image files that are delivered in a file or
in the message body. The second filter describes the support for bb.action.OPEN and bb.action.VIEW
actions on any URI file with .jpg or .png extensions.
<invoke-target id="com.example.image.view">
<entry-point-id></entry-point-id>
<invoke-target-type>application</invoke-target-type>
<filter>
<action>bb.action.VIEW</action>
<action>bb.action.OPEN</action>
<mime-type>image/png</mime-type>
<mime-type>image/jpeg</mime-type>
<property var="uris" value="file://,data://local"/>
</filter>
<filter>
<action>bb.action.VIEW</action>
<action>bb.action.OPEN</action>
<mime-type>*</mime-type>
<property var="uris" value="file://"/>
<property var="exts" value="jpg,png"/>
</filter>
</invoke-target>
In this section, you will learn how brokering and selection works, to help you determine the best way to
configure your target filters.
When a client application queries the invocation framework for a suitable target or when it sends an unbound
invocation request, the invocation framework determines the set of suitable targets by comparing the
invocation request to all of the installed target filters defined for the applications on the BlackBerry device. This
process is called invocation brokering. Brokering uses a set of rules to determine how to match the invocation
request to each filter. Specifically, a filter is considered a match only if both the action rules and the data rules
are satisfied.
• The action specified in the invocation request matches one of the actions that are specified in the target
filter.
• If the invocation request does not specify an action, all filters are considered to be an action match.
Adding Features 97
If the target filter does not contain declaration of any actions, then it doesn't match any invocation requests.
The URI and MIME type are considered when the invocation data is matched. URI matching involves
comparing of the uris and exts attributes of the target filter with the uri attribute of the invocation request.
Likewise, if the target filter specifies exts values, then that app is considered a match only if one of the exts
values is the suffix of the uri path that is provided in the invocation request.
Note: The invocation framework adds a dot separator between the specified exts value and the rest of the
path automatically when it performs the comparison.
A MIME type comparison is performed between the MIME type provided in the invocation request and the
MIME type that is provided in the target filter. Both the invocation request and the target filter may use a
wildcard character (*) in the subtype of the MIME type. Here are some factors that determine whether a target
filter is considered a MIME type match:
• The URI and MIME type specified in the invocation request match with the target filter's uri and ext.
• The wildcard character (*) is considered and is used for MIME type matching.
• If the MIME type is specified then the type is not inferred from the uri.
• The absence of a declared ext in the target filter implies an ext match.
• The absence of the uri in either the invocation request or the target filter implies that the data attribute is
data://local.
• If the invocation request does not specify a MIME type and a target filter declaration has matching URIs and
file extensions, then the invocation framework considers that target filter for a MIME type match.
• If the invocation request does not specify a uri while the target filter declared a matching MIME type but
either did not declare a uri, which implies that the data attribute is data://local, or explicitly declared
the uri as uri=data://local, then the target filter is considered a MIME type match.
Unbound selection
When an unbound invocation has multiple targets that are suitable, the invocation framework chooses
a best fit target to invoke by using the brokering rules. Here are the rules that the selection process follows:
• The filter that has the strongest URI match based on its length is selected.
• When target filters are compared, only the scheme attribute is used for the URIs that are declared in the
config.xml file.
• If more than one target filter has the longest matching URI, then the target filter with the strongest MIME
type match is selected. The type with the wildcard character (*) is considered the weakest match, the
subtype with the wildcard character type/* is considered weak, while a match without wildcard
characters is considered the strongest match.
Adding Features 98
• If more than one target filter has the strongest MIME type match, then the target filter with an exts match
is selected if the uri attribute is defined in file://scheme format.
• If more than one target filter has a matching ext, then the filter that the system marks as default for that
set of target filter criteria is selected.
• If no target filter is identified as default, then the oldest target filter is selected as the best possible match.
Cards
A card allows an application to export its application screen to another application. Unlike an application,
which may offer a full and rich set of features, a card typically provides the ability to perform specific tasks
such as picking a contact, composing an email or previewing an image. To a user, a card appears as part of the
client application and does not appear separately in Active Frames. An application can embed only one card at
a time. However, one card can embed another card, which allows the application to create a stack of cards
that appear as part of the client application. Although the card appears as part of the client application, it
maintains its own process and security context. In the following sections, you will learn how to create and use
cards in your application, as well as how to expose them to other apps.
Card styles
When an application imports a card, the BlackBerry 10 OS controls the visual transition on and off the screen,
but it also controls the peek behavior that allows the user to look at the card under the card that's currently
displayed. The BlackBerry 10 OS manages the transition and the peek behavior based on the card's style.
Composers, pickers, and previewers
You can use three different styles of card in your application: composers for creating and editing content,
pickers for choosing existing content, and previewers for viewing existing content. The style of card you use
determines how the BlackBerry 10 OS transitions between the application and the card, how peeking is
handled, and determines the general task that a card performs. Each card style has associated visual style
guidelines.
Card transitions
A card transitions on or off the screen in a beautiful animation. The cards appears on the screen as either
sliding in from the bottom or from the right side. Previewers slide in from the right side, while composers and
pickers slide in from the bottom of the screen.
Adding Features 99
Transition style of composers and pickers
Peeking is the ability for a user to see under a card, by using a gesture. There are two ways in which a user can
peek under the card:
• Parent peek: The user slides a finger right to reveal the screen that lies immediately under the card.
• Root peek: The user slides a finger right on the action bar to reveal the application at the bottom of the
stack of cards.
To verify a great user experience, here are some guidelines to consider if you want to use cards in your app:
To learn what the action bar, context menu, and buttons are, see the basics.
Note:
When you create a card, you must add support for both landscape and portrait orientation so that the card
follows the orientation of your application.
Card invocation
Cards enhance the invocation framework's capabilities by allowing applications to share the UI and the
application logic with other applications. You send a request to invoke a card in the same way as an invocation
request for an application, which means that everything that you learned about sending an invocation request,
Here's how you can use the invocation framework to import a card from another application:
blackberry.invoke.invoke({
target: "com.acme.myapp",
action: "bb.action.VIEW",
type: "image/png",
uri : "file://path/to/image.png"
}, onInvokeSuccess, onInvokeError);
Before a new card is invoked and allowed to be stacked, the platform verifies that the client application is not
already parenting a card. Unlike an application, a card may continue to exist in multiple instances, but a
parent application (or a card) can parent only one card at a time. This is important to consider, since multiple
instances of a card may be running at the same time.
Cards support a "fire and forget" import model. However, for applications that require notifications and
additional feedback, cards also provide peek notifications and response data.
Cards offer a parent card or an application the ability to receive notifications when a user peeks at another
card. This is important if you want your application to display content differently during a peek event. Here is
how you can enable your application to listen for peek events:
function onChildCardStartPeekHandler(peekType) {
console.log("The card started peeking.");
if (peekType == "root") {
updateContent(true);
}
}
function onChildCardEndPeekHandler() {
console.log("I am no longer being peeked at.");
}
document.addEventListener("onChildCardStartPeek",
onChildCardStartPeekHandler);
document.addEventListener("onChildCardEndPeek", onChildCardEndPeekHandler);
A card can send a response message to the parent application when a card completes its task. For example, a
picker card can return the data, that a user selects, to the client application. Here's how you can listen for card
response messages:
function onCardClosedHandler(info) {
console.log("Card was closed: " + info);
}
document.addEventListener('onChildCardClosed',onCardClosedHandler);
Typical card usage for previewers and many composers does not involve a response. Therefore, a best practice
is to design your previewer and composer cards in such a way that any response is optional.
Close a card
An application may request to close a card that it imported. As a result the card is transitioned off screen.
When a user closes the card, both the application and the card are notified. However, if the card is closed by
the application itself, the card cannot provide a response. Also, when an application closes a card, it closes the
entire stack of cards (including children of the card) above it. Here's how your application can request to close
a child card:
blackberry.invoke.closeChildCard();
To learn more about APIs that support card invocation and read code samples, see card.
You just learned how you can integrate the functionality of other applications with yours by using cards.
However, a great way to get your application noticed is to export your application's cards, so other applications
can import them. Creating cards is similar to creating a small, focused application. One of the key differences,
however, is that unlike an application, a card can have multiple instances running at the same time. The
BlackBerry 10 OS creates a new instance for each client application. In many cases, the BlackBerry 10 OS will
pool your card (pooling is discussed a bit later). This section can help you understand how you can use cards to
expose your application's functionality to other applications.
A card shares an execution context across multiple instances of itself. For example, all instances of a card run
in the same workspace directory and permissions. This feature of cards is important when you consider how
you use your resources. If you read and write files, make sure you coordinate and access across different
instances of your card. Any cards your application exports are packaged in the same .bar file as the
application.
Since a card is used through an invocation request, the first step in exporting a card is to register an invocation
target for it. Registering card targets is exactly the same as registering application targets except for a minor
difference. The <invoke-target-type> tag must specify one of the card styles supported by the
BlackBerry 10 OS. The valid values for <invoke-target-type> are card.previewer,
Just like applications, cards are packaged and identified as invocation targets in the config.xml file. Here's an
example that shows you how to declare cards:
<invoke-target id="com.acme.myapp">
<invoke-target-type>card.previewer</invoke-target-type>
<filter>
<action>bb.action.VIEW</action>
<action>bb.action.SHARE</action>
<mime-type>image/png</mime-type>
<mime-type>image/jpeg</mime-type>
<property var="uris" value="file://"/>
</filter>
</invoke-target>
After a card finishes its task, it can request to be closed. When this request is processed, the card is
transitioned off the screen and its parent application is notified. While the card closes itself, it can also send a
response message to the parent application.
You can create your cards in such a way that they can be pooled when a user closes the card. Pooling helps to
keep frequently used cards ready for reuse, which reduces loading and transition time when cards are
stacked. For example, if the user is viewing one email message after another, instead of exporting a new card
for every email, the BlackBerry 10 OS may pool the existing email previewer card and use it again.
When you're creating a card, you must consider several things before you handle pooling events, such as
which resources your cards should clean up or keep when they're pooled. First, consider adding support for
purging the state of the card. While pooled cards are not terminated, they may be suspended to keep them
from processing while pooled. Once your card is pooled it should release resources such as files or database
connections until it is resumed again. When a card receives a cardPooled notification it should clear its
current state and listen for future invocations. In addition, cards must be written to support multiple instances
which run simultaneously within the same sandbox.
Second, if an application with cards defines several card targets, then when it's retrieved from the pool, the
card may be invoked to service any of the declared targets. In other words, if a .bar file bundles a composer,
previewer, and picker under a single entry point, then when it's retrieved from the pool, the application or card
may be invoked as any of these targets.
A card’s orientation is aligned with the orientation of the parent application. If the parent application's
orientation is fixed, any child cards in the stack also have a fixed orientation.
When you create cards, you must add support for both landscape and portrait orientation so that the card
follows the orientation of your application.
Card security
Cards have their own identity and sandbox environment that is shared with all instances of the card. Like
applications, cards are processed in their own context and with their own permissions. It is important to pay
attention to the capabilities and the data that you want to expose using your card.
To learn more about APIs that support card invocation and read code samples, see card.
Menu integration
BlackBerry 10 OS offers a well-integrated menu system that enables you to make highly contextual apps.
There are two types of menus available on the UI of a BlackBerry 10 OS device: action menu and context
menu.
In this section, you will learn how to add menus to your app and how to use the invocation framework to display
your application in the context menu of other apps. You will also learn about configuring your app to allow the
BlackBerry 10 OS to automatically populate any related actions into the context menu of your app.
It's a good practice to add invocation-related actions to the context menu. However, if an action applies to the
whole page, you can add the action to the action bar.
Meanwhile, to learn more about the action and application menus, see Menus.
Context menu
The context menu is a vital part of building an intuitive experience and is a key feature in BlackBerry 10 OS. It
is presented when the user presses and momentarily holds a particular area of the application UI. The context
menu is divided into two sections that offer actions related to the content selected by the user.
The upper half of the context menu is the application section, which contains all the actions that the
application adds. For example, in the following image on the right, Add as friend, Call, Email, and Text actions
are all application actions.
The lower half of the context menu is the platform section, which contains all the actions that the BlackBerry
10 OS adds automatically. In the following image on the right, Call, Email, Text, Share, Set as and Open in are
platform actions.
To learn about enabling and customizing the context menu, see the API documentation on context menu.
You can add a specific functionality of your application to the platform section of the context menu of other
apps. Enabling your application to appear in the platform section allows it greater visibility among other
applications and is good for the publicity of your app. You can add a specific functionality of your application to
the platform section by declaring support for the invocation of a core action for a given context. The following
core actions are available in the BlackBerry 10 OS:
• bb.action.OPEN
• bb.action.SHARE
• bb.action.SET
It is important to choose the action that suits your application's needs. For example, if your application
manages images, then supporting bb.action.OPEN action in your app is a good idea. If your app uploads
images to an online catalog, then you probably want to support bb.action.SHARE. If your app assigns
images as avatars, you probably want to use bb.action.SET as the core action.
Here's how you can declare these actions in the target filter section of the config.xml file of your application:
<invoke-target id="com.example.image.view">
<invoke-target-type>application</invoke-target-type>
<invoke-target-name>My Sample Application</invoke-target-name>
<icon>
<image public="true"> icon_small.png</image>
For more information about invocation and how you can make your app an invocation target, see Receiving
invocation.
If your application is declaring itself as a target for core menu actions (OPEN, SHARE, SET), you must package
your application with two images of size 81 x 81 pixels and 358 x 358 pixels respectively. These images should
typically show your application's icon. The image of size 81 x 81 pixels is used in the list that displays all the
available targets while the image of size 358 x 358 pixels is used in the suggestions section of the target
selection menu.
Here's how the images for BBM and Text Messages applications look in the list section:
Here's how the images for Email and Text Messages applications look in the suggestions section:
Note: As a best practice, remember to fill any transparent pixels in your image with color. This prevents the
background color of the suggestions grid from appearing through the transparent pixels.
You should specify the images in the config.xml file of your application as shown in the code below.
...
<icon>
<image public="true"> icon_small.png</image>
<image public="true"> icon_big.png</image>
</icon>
...
On devices that use BlackBerry Balance technology, the app with the active text and the app being
invoked must be in the same space (personal or work).
To use a URI pattern, you specify the start of a URI. This can be the scheme portion alone (for example,
myuri:) or it can be a longer form (for example, myuri:createid). Strings in native UI controls become
active text elements if they start with this pattern, conform to the syntax of a URI, and an invocation filter is
specified, as described below. In BlackBerry WebWorks applications, you must specify text patterns within an
anchor element.
Patterns are specified in the config.xml file using the <invoke-target> element. Here's an example that
shows an invocation request that contains a URI pattern:
<invoke-target id="com.mycompany.myapplication">
<type>APPLICATION</type>
<filter>
<action>bb.action.VIEW</action>
<mime-type>*</mime-type>
<property var="uris" value="activetext:"/>
</filter>
<invoke-target-pattern>
<pattern-value type="uri">activetext:</pattern-value>
</invoke-target-pattern>
</invoke-target>
Attribute Description
<invoke- The invocation parameters of
target> your app. For more
information about <invoke-
target>, see Target
declaration.
<type> Can be APPLICATION or
CARD.
To link to an active text target from a WebWorks app, add an anchor tag to your HTML source.
To get the value of an active text invocation, check the uri property in the invoked callback.
Media Player
BlackBerry Browser
Miracast card
BlackBerry World
NFC
Phone
Bluetooth
Calendar Pictures
Camera
Picture editor
Remember
Clock
Settings
Device Monitor
YouTube
LinkedIn
Adobe Reader
Here are the invocation attributes you use to open a .pdf file in the Adobe Reader application:
Action bb.action.OPEN
URI file:///path/to/my/content.pdf
Here are the invocation attributes you use to open a .pdf file in a previewer card:
Attribute Value
Target ID com.rim.bb.app.adobeReader.viewer
Action bb.action.VIEW
URI file:///path/to/my/content.pdf
BBM
Here are the invocation attributes you use to share a file with BBM:
Action bb.action.SHARE
URI file:///path/to/my/content.doc
Here are the invocation attributes you use to open the BBM application:
Attribute Value
Target ID sys.bbm
Action bb.action.OPEN
Here are the invocation attributes you use to set a picture as a BBM display picture:
Attribute Value
Target ID sys.bbm.imagehandler
Action bb.action.SET
URI file:///path/to/my/content.jpg
Here are the invocation attributes you use to share text with BBM:
Action bb.action.SHARE
Here are the invocation attributes you use to share text or an image with BBM Groups:
Attribute Value
Target ID sys.bbgroups.sharehandler
Action bb.action.SHARE
URI file:///path/to/my/content.txt or
file:///path/to/my/image.png
Here are the invocation attributes you use to invite a user to BBM or to start a BBM chat:
Attribute Value
Target ID sys.bbm.sharehandler
Action bb.action.BBMCHAT
Note:
This invocation action will either display an Invite to BBM screen or the BBM chat composer screen
depending on whether the specified PIN is already a BBM contact.
Here are the invocation attributes you use to invite a user to BBM:
Attribute Value
Target ID sys.bbm.sharehandler
Action bb.action.INVITEBBM
URI pin:<pin>
Here are the invocation attributes you use to start a BBM audio or a video chat with a contact:
Attribute Value
Target ID sys.service.videochat
Action bb.action.OPEN
Here are the invocation attributes you use to invoke your BBM Channel from within your app:
Attribute Value
Target ID sys.bbm.channels.card.previewer
Action bb.action.OPENBBMCHANNEL
Here are the invocation attributes you use to share a text or an image with BBM Channels:
Attribute Value
Target ID sys.bbm.channels.sharehandler
Action bb.action.SHARE
URI file:///path/to/my/content.doc,
file:///path/to/my/image.jpg
Here are the invocation attributes you use to start a multi-person chat in BBM:
Action bb.action.BBMCONF
"conference": {
"contacts" : [
{ "pin" : "1234ABCD" },
{ "pin" : "1234567A" },
]}
When sending data, you must specify the contact's PIN in the pin field.
Note: API support for starting a group chat in BBM is available in the 10.1 (and later) version of the BlackBerry
10 Native SDK.
BlackBerry Browser
Opening a URL
Attribute Value
Target ID sys.browser
MIME type Any valid MIME type value
Action bb.action.OPEN
URI • http://
• https://
• ftp://
Here are the invocation attributes you use to open local content:
Attribute Value
Target ID sys.browser
MIME type • text/html
• application/xhtml+xml
• image/svg+xml
Action bb.action.OPEN
File extensions • htm
• html
• xhtml
• svg
URI file://
BlackBerry World
Here are the invocation attributes you use to open a specific page in BlackBerry World:
Attribute Value
Target ID sys.appworld
Action bb.action.OPEN
Here's a list of URIs you use to open various other pages in BlackBerry World:
Page URI
Home page appworld://
Bluetooth
Here are the invocation attributes you use to invoke a Bluetooth card to share a local file:
Attribute Value
Target ID sys.btviewer
Action bb.action.SHARE
[
{
"uri": "file:///path/to/file"
},
...
]
Calendar
Creating an event
Here are the invocation attributes you use to launch a calendar card to create an event:
Attribute Value
Target ID sys.pim.calendar.viewer.eventcreate
Action bb.action.CREATE
Here are the invocation attributes you use to launch a calendar card to pick an existing event:
Attribute Value
Target ID sys.pim.calendar.viewer.nav
Action bb.calendar.PICK
Card response:
Here are the invocation attributes you use to launch a calendar card to edit an existing event:
Action bb.calendar.EDIT
Description Data
Account ID of the existing event unsigned int accountId
Folder ID of the event (optional) unsigned int folderId
Event ID unsigned int eventID
Start time of the event (optional) QString startTime
Note: startTime lets you differentiate between any two or more recurring events that have the same
eventID.
Here are the invocation attributes you use to launch a calendar card to view an .ics file:
Attribute Value
Target ID sys.pim.calendar.viewer.ics
Action bb.action.OPEN
URI file:///path/to/my/file/filename.ics
Here are the invocation attributes you use to open the calendar app:
Attribute Value
Action bb.calendar.OPEN
MIME type text/calendar
Data "data":"file:///path/to/file.txt"
Here are the invocation attributes you use to launch a calendar card to view an existing event:
Attribute Value
Target ID sys.pim.calendar.viewer.ics
Action bb.calendar.OPEN
Here are the invocation attributes you use to open the calendar app to view an existing event:
Attribute Value
Action bb.calendar.VIEW
MIME type text/calendar
Data "data":"file:///path/to/file.txt"
To learn more about invoking calendar cards and read code samples, see the API documentation on calendar
event composer and calendar event picker cards.
Camera
Here are the invocation attributes you use for opening the Camera card:
Attribute Value
Target ID sys.camera.card
Action bb.action.CAPTURE
save Include a full path to the saved file. This response is returned if a card
is closed after a user takes a
picture or records a video. The
captured file is returned in the data
field of the message.
Here are the invocation attributes you use for invoking the Camera application:
Attribute Value
Target ID sys.camera.app
Action bb.action.CAPTURE
When the camera application is opened, it is not locked to any particular mode, regardless of the data
parameter's description. The user can change the mode of the Camera application at any time. For example, a
user can choose between the photo capture mode, video capture mode, and the timeshift mode. Also, if an
Clock
Here are the invocation attributes you use to open the clock app:
Attribute Value
Target ID bb.clock.launcher
Action bb.action.VIEW
Data Description
alarmClockPane Launches the alarm clock view
worldClockTab Launches the world clock view
stopwatchTab Launches the stopwatch view
timerTab Launches the timer view
Contacts
Viewing a contact
Here are the invocation attributes you use to launch the contacts app to view a contact:
Attribute Value
Target ID sys.pim.contacts.app
Action bb.action.OPEN
Here are the invocation attributes you use to launch the contacts app to add a new contact:
Attribute Value
Target ID sys.pim.contacts.app
Action bb.action.ADDTOCONTACT
Here are the invocation attributes you use to open a vCard contact attachment (.vcf file) using a contact
previewer card:
Attribute Value
Target ID sys.pim.contacts.card.viewer
Here are the invocation attributes you use to launch the contacts app to open a vCard contact attachment (.vcf
file):
Attribute Value
Target ID sys.pim.contacts.app
Action bb.action.OPEN
Here are the invocation attributes you use to create a new contact using a contact composer card:
Attribute Value
Target ID sys.pim.contacts.card.composer
Action bb.action.CREATE
Here are the invocation attributes you use to edit an existing contact using a contact composer card:
Action bb.action.EDIT
Here are the invocation attributes you use to view a contact using a contact previewer card:
Attribute Value
Target ID sys.pim.contacts.card.viewer
Action bb.action.VIEW
Here are the invocation attributes you use to set a picture of an existing contact:
Attribute Value
Target ID sys.pim.contacts.setcontactpicture
Device Monitor
Here are the invocation attributes you use for the Device Monitor app:
Attribute Value
Target ID sys.SysMon.app
Action bb.action.OPEN
Here are the invocation attributes you use for the Device Monitor card:
Attribute Value
Target ID sys.SysMon.card
Action bb.action.VIEW
Here's a list of URIs you can use to invoke the Device Monitor card or the app:
Battery devicemonitor://battery
Storage devicemonitor://storage
Memory devicemonitor://memory
Here's an example to show how you can invoke the Device Monitor app:
<invoke-target id="sys.SysMon.app">
<entry-point-id>sysmon_app</entry-point-id>
<invoke-target-type>APPLICATION</invoke-target-type>
<filter>
<action>bb.action.OPEN</action>
<mime-type>*</mime-type>
<property var="uris" value="devicemonitor://"/>
</filter>
</invoke-target>
Here's an example to show how you can invoke the Device Monitor card:
<invoke-target id="sys.SysMon.card">
<entry-point-id>sysmon_app</entry-point-id>
<invoke-target-type>card.previewer</invoke-target-type>
<filter>
<action>bb.action.VIEW</action>
<mime-type>*</mime-type>
<property var="uris" value="devicemonitor://"/>
</filter>
</invoke-target>
Docs to Go
Opening a spreadsheet
Here are the invocation attributes you use to open a spreadsheet in a previewer card:
Action bb.action.VIEW
URI file:///path/to/my/content.xls
Here are the invocation attributes you use to open a spreadsheet file in the Docs to Go application:
Attribute Value
Target ID sys.dxtg.stg
Action bb.action.OPEN
URI file:///path/to/my/content.xls
, application/vnd.ms-
excel.sheet.macroEnabled.12,
application/vnd.ms-
excel.template.macroEnabled.12
Opening a presentation
Here are the invocation attributes you use to open a presentation in a previewer card:
Attribute Value
Target ID sys.slideshowtogo.previewer
Action bb.action.VIEW
URI file:///path/to/my/content.ppt
Here are the invocation attributes you use to open a presentation file in the Docs to Go application:
Attribute Value
Target ID sys.dxtg.stg
Action bb.action.OPEN
URI file:///path/to/my/content.ppt
Opening a document
Here are the invocation attributes you use to open a document in a previewer card:
Action bb.action.VIEW
URI file:///path/to/my/content.doc
Here are the invocation attributes you use to open a document file in the Docs to Go application:
Attribute Value
Target ID sys.dxtg.stg
Action bb.action.OPEN
URI file:///path/to/my/content.doc
ate, application/vnd.ms-
word.document.macroEnabled.12,
application/vnd.ms-
word.template.macroEnabled.12
Sharing a file
Attribute Value
Target ID sys.pim.uib.email.hybridcomposer
Action bb.action.SHARE
URI file:///path/to/file
Here are the invocation attributes you use to share an .ics file:
Attribute Value
Target ID sys.pim.uib.email.hybridcomposer
Action bb.action.SHARE
Sharing text
Here are the invocation attributes you use to share text through an email composer:
Attribute Value
Target ID sys.pim.uib.email.hybridcomposer
Action bb.action.SHARE
Here are the invocation attributes you use to share multiple files through an email composer:
Attribute Value
Target ID sys.pim.uib.email.hybridcomposer
Action bb.action.SHARE
URI list://
[
{
"uri": "file:///path/to/file"
},
...
]
Here are the invocation attributes you use to compose an email with prepopulated fields using a mailto:
URI:
Attribute Value
Target ID sys.pim.uib.email.hybridcomposer
For the URI attribute, use a standard mailto: URI and make sure that the entire URI is percent-encoded.
If you want to prepopulate the recipient field with more than one entry, use the following format:
mailto:address1@domain.com?to=address2@domain.com
If you want to prepopulate the CC, BCC, subject, and the message body fields, use the following format:
mailto:address@domain.com?cc=address2@domain.com&bcc=
address3@domain.com&subject=A%20Subject&body=That%20body
Here are the invocation attributes you use to compose an email with prepopulated fields using data in JSON
format:
Attribute Value
Target ID sys.pim.uib.email.hybridcomposer
Action bb.action.COMPOSE
{
"to" : ["a@a.com", "b@b.net"],
"accountid" : 1234,
"cc" : ["foo@bar.com", "stuff@place.com"],
"bcc" : ["foo@bar.com", "stuff@place.com"],
"subject" : "Some punctuation. Symbol in the $ubject!!",
"body" : "HI! Here is some more stuff.\n\n14% of emails have #1 newline
or
stuff* @ home.\n",
"attachment" : ["file:///path/to/my/item.txt"]
}
The accountid field in the code above represents the account ID that is used as a default value for the
composer card.
Here are the invocation attributes you use to reply to, reply to all, and forward an existing message:
Attribute Value
Target ID sys.pim.uib.email.hybridcomposer
The URI points to the message that is being replied to or being forwarded and is sent in the following format:
pim:message/rfc822:[accountID]:[messageID]
Here are the invocation attributes you use to view an existing message:
Action bb.action.VIEW
The URI points to the message that is viewed and is sent in the following format:
pim:message/rfc822:[accountID]:[messageID]
All the invocation attributes related to the Facebook app require a Facebook account to be set up on the
device.
Here are the invocation attributes you use to share text with Facebook:
Attribute Value
Target ID Facebook
Action bb.action.SHARE
Here are the invocation attributes you use to share media (pictures and video) with Facebook:
Action bb.action.SHARE
URI file:///path/to/content.png
File extensions .gif, .jpeg, .jpg, .png, .psd, .tiff,
.tif, .3g2, .3gp, .
3gpp, .asf, .avi, .dat, .flv, .m4v, .
mkv, .mod, .mov, .mp4, .mpe, .mpeg4,
.mpg, .nsv, .ogm, .ogv, .qt, .tod, .v
ob, .wmv
MIME type MIME type can specified in the following format:
image/gif, image/jpeg, video/mov, video/
mpeg4, and so on
Here are the invocation attributes you use to share a URL with Facebook:
Attribute Value
Target ID Facebook
Action bb.action.SHARE
Entry Description
object_type
Specifies the type of the profile (for example, page
for a business profile or user for a personal profile.
Here's an example that shows how you can open a business profile page:
blackberry.invoke.invoke( {
target: "com.rim.bb.app.facebook",
action: "bb.action.OPEN",
metadata: JSON.stringify
({object_type : 'page' , object_id : '328506290597521'})
}, onSuccess, onError );
Foursquare
Here are the invocation attributes you use to open a single sign-on card:
Attribute Value
Target ID com.foursquare.blackberry.sso.card
Action bb.action.VIEW
Here are the invocation attributes you use to search for a venue:
Attribute Value
Target ID com.foursquare.blackberry.venuesearch
.card
Action bb.action.VIEW
URI "foursquare://venues/search?
oauth_token=" + accessToken
Exploring a venue
Attribute Value
Target ID com.foursquare.blackberry.uri
Action bb.action.OPEN
URI foursquare://venues/explore
Here are the invocation attributes you use to open a venue card:
Action bb.action.OPEN
Here are the invocation attributes you use to open a check-in card:
Attribute Value
Target ID com.foursquare.blackberry.uri
Action bb.action.OPEN
Here are the invocation attributes you use to open a user profile:
Attribute Value
Target ID com.foursquare.blackberry.uri
Action bb.action.OPEN
Here are the invocation attributes you use to open the friend requests:
Attribute Value
Target ID com.foursquare.blackberry.uri
Action bb.action.OPEN
URI foursquare://users/requests
Here are the invocation attributes you use to open the friend suggestions:
Attribute Value
Target ID com.foursquare.blackberry.uri
Action bb.action.OPEN
URI foursquare://users/suggest?
type=friend
Here are the invocation attributes you use to open page suggestions:
Action bb.action.OPEN
URI foursquare://users/suggest?type=page
Adding friends
Here are the invocation attributes you use to add friends from Contacts, Twitter, Facebook, or Search:
Attribute Value
Target ID com.foursquare.blackberry.uri
Action bb.action.OPEN
URI foursquare://users/addfriends?
from=phonebook
All the invocation attributes related to the LinkedIn app require a LinkedIn account to be set up on the device.
Here are the invocation attributes you use to share text with LinkedIn:
Attribute Value
Target ID LinkedIn
Action bb.action.SHARE
Here are the invocation attributes you use to open a LinkedIn profile:
Attribute Value
Target ID com.linkedin.urihandler
Action bb.action.VIEW
URI linkedin:contact:<public_URL_of_the_L
inkedIn_profile_page>
Maps
You can invoke BlackBerry Maps by using the Invoke API with the following invocation attributes:
Attribute Value
Action bb.action.OPEN
MIME type application/vnd.rim.map.action-v1
The MIME type above defines all the actions that BlackBerry Maps handles. For example, setting the map
center or starting navigation mode. The data passed in the invocation request is in JSON format.
In addition to the action and MIME type attributes mentioned above, you can use the following data attributes
to invoke the BlackBerry Maps app to display a single location on the map.
blackberry.invoke.invoke(
{
action: "bb.action.OPEN",
type: "application/vnd.rim.map.action-v1"
}
);
Launching the Maps app and getting the current device location
blackberry.invoke.invoke(
{
action: "bb.action.OPEN",
type: "application/vnd.rim.map.action-v1",
data: JSON.stringify(
{
"geolocation": true
}
)
}
);
Launching the Maps app and centering the map at a particular location
blackberry.invoke.invoke(
{
action: "bb.action.OPEN",
type: "application/vnd.rim.map.action-v1",
data: JSON.stringify(
{
"center": {
"latitude": 43.4667,
"longitude": -80.5167,
"altitude": 2000
}
Adding Features 152
}
)
}
);
blackberry.invoke.invoke(
{
action: "bb.action.OPEN",
type: "application/vnd.rim.map.action-v1",
data: JSON.stringify(
{
"placemark": {
"latitude": 43.4667,
"longitude": -80.5167,
"name": "Waterloo",
"description": "Waterloo, Ontario, Canada"
}
}
)
}
);
You can use the following data attributes to invoke the BlackBerry Maps app in navigation mode.
nav_start.longitude or [-180.0,180.0]
Longitude of the start or end
nav_end.longitude location.
blackberry.invoke.invoke(
{
action: "bb.action.OPEN",
type: "application/vnd.rim.map.action-v1",
data: JSON.stringify(
{
"view_mode": "nav",
"nav_end":
{
"properties":
{
"name": "Toronto",
"description": "City of Toronto",
"address": "Toronto, Ontario, Canada"
},
"latitude": 43.7,
"longitude": -79.4
}
}
)
}
);
blackberry.invoke.invoke(
{
action: "bb.action.OPEN",
type: "application/vnd.rim.map.action-v1",
data: JSON.stringify(
{
"view_mode": "nav",
To display uncompressed KML data on the map, you can use application/vnd.google-earth.kml
+xml as the MIME type. Here's an example:
blackberry.invoke.invoke(
{
action: "bb.action.OPEN",
type: "application/vnd.google-earth.kml+xml",
data: "<?xml version=\"1.0\" encoding=\"UTF-8\"?>
<kml xmlns=\"http://www.opengis.net/kml/2.2\"><Placemark>
<name>Title</name>
<description>Description</description><Point>
<coordinates>-75.930417,45.342533,0</coordinates>
</Point></Placemark></kml>"
}
);
Here are the invocation attributes you use to open audio or video files:
Attribute Value
Target ID sys.mediaplayer.previewer
MIME type All supported audio and video files
Action bb.action.VIEW
URI • file://
• http://
Data Description
contentTitle The title that's displayed in the viewer title field.
imageUri The URL of the image source that replaces the
default background image. This attribute is useful for
audio content.
The invocation attributes you use to open audio or video files with the Media Player application require the
same set of attributes as the ones you use for the Media Player cards, except for the target ID:
Attribute Value
Target ID sys.mediaplayer.previewer.app
Miracast card
A Miracast card can be invoked to discover and establish a connection to a nearby Miracast device. You can
invoke the Miracast card in two modes: play on and show on.
In ShowOn mode, the application is not aware of the streaming. The content is streamed to a Miracast device
in the native resolution of the BlackBerry device. Here are the invocation attributes you use to invoke the
Miracast card to show your content on a Miracast device:
Attribute Value
Target ID sys.miracastviewer
Action bb.action.VIEW
In PlayOn mode, your application renders content to a Miracast device at a resolution that can be different
from the native resolution of the BlackBerry device. Here are the invocation attributes you use to invoke the
Miracast card to play your content on a Miracast device:
Attribute Value
Target ID sys.miracastviewer
Action bb.action.VIEW
NFC
Here are the invocation attributes you use to invoke an NFC card to share a single local file or a URI:
Attribute Value
Target ID sys.NFCViewer
Here are the invocation attributes you use to invoke an NFC card to share a set of files or URIs:
Attribute Value
Target ID sys.NFCViewer
Action bb.action.SHARE
URI list://
[{
"uri":<file-uri>,
"type":<mime-type>,
"data":<metadata>
}]
In the above code, the uri is the local path to the file,
type is the MIME type for the specified file, and
data is the associated metadata for the specified file
(for example, thumbnail).
Sharing text
Here are the invocation attributes you use to invoke an NFC card to share text:
Attribute Value
Target ID sys.NFCViewer
Action bb.action.SHARE
Here are the invocation attributes you use to invoke an NFC card to share NFC Data Exchange Format (NDEF)
messages:
Attribute Value
Target ID sys.NFCViewer
Action bb.action.SHARE
Sharing URLs
Here are the invocation attributes you use to invoke an NFC card to share URLs, including remote files (for
example, http://aa.mp3):
Attribute Value
Target ID sys.NFCViewer
Action bb.action.SHARE
Here are the invocation attributes you use to invoke an NFC card to share your application's custom data or
share an image or a document as a URL:
Attribute Value
Target ID sys.NFCViewer
Action bb.action.SHARE
Phone
Here are the invocation attributes you use to open the call log. If you don't specify the call log in the MIME type,
the full call log list is displayed.
Attribute Value
Data Optional integer of a call log ID
Action bb.action.OPEN
Dialing a number
Attribute Value
MIME type application/
vnd.blackberry.phone.startcall
Data Description
String number (required) The phone number that will be called.
int line_id (optional) Line ID to use.
int contact_id Contact ID of the party being called. If you don't
specify this field, the contact information is looked up
based on the phone number.
Boolean apply_smart_dialing Whether to apply smart dialing. Default is true.
Here are the invocation attributes you use to dial an emergency number:
Attribute Value
MIME type application/
vnd.blackberry.phone.startcall
Action bb.action.EMERGENCY_CALL
Pictures
Opening images
Here are the invocation attributes you use to open images with the picture previewer:
Action bb.action.VIEW
URI file:///
Picture editor
Here are the invocation attributes you use to invoke the Picture editor card:
Attribute Value
Target ID sys.pictureeditor.cardeditor
Action bb.action.EDIT
URI file:///path/to/content.jpg
You can configure the size of the output image by using the size and the upScale parameters. The size
parameter allows you to specify the dimensions of the output image in pixels while the upScale parameter
identifies whether the output image is scaled to that specified size or not. The upScale parameter is only valid
Depending on how you use these two parameters, you will have one of the three outcomes mentioned below.
In this case, size and upScale parameters are not used. This allows the user to crop the image to any size or
aspect ratio. On opening, the Picture editor's filter tab opens by default for this case. This use case is
demonstrated in the Pictures app of the BlackBerry 10 OS.
To specify an exact size for the output image, you must specify a value for the size parameter and set the
upScale parameter to true. The value for the upScale parameter can also be omitted since true is the
default value.
In this case, the size of the output image is exactly the same as specified by the size parameter. On opening,
the Picture editor's transform tab opens by default for this case. The output image is cropped to the same
aspect ratio as the size. This also means that the user will not be able to change the aspect ratio of the output
image as the buttons to change the aspect ratios are disabled in the Picture editor.
When saving the output image, if the size of the edited image is different from the specified size, the output
image is automatically scaled to the specified size. This use case is demonstrated in the Contacts app of the
BlackBerry 10 OS.
To specify a maximum limit for the size of the output image, you must specify a value for the size parameter
and set the upScale parameter to false.
In this case, the size of the output image can be smaller but never exceed the size specified in the size
parameter. On opening, the Picture editor's transform tab opens by default for this case. The output image is
cropped to the same aspect ratio as the size. This also means that the user will not be able to change the
aspect ratio of the output image as the buttons to change the aspect ratios are disabled in the Picture editor.
When saving the output image, if the size of the edited image is larger than the size parameter specification,
it is automatically downscaled to the specified size. However, if the size of the edited image is smaller than
the size parameter specification, the output image size remains the same. This use case is demonstrated in
the BBM app of the BlackBerry 10 OS.
Remember
Here are the invocation attributes that you use to launch a Remember card to create a new entry:
Action bb.action.ADD
URI remember://notebookentry
• title=<ENTRY TITLE>
• description=<ENTRY DESCRIPTION>
• duedate=<# SECONDS SINCE EPOCH>
• status=NotActionable, Completed,
NotCompleted
• notebookid=<ACCOUNT KEY>:<NOTEBOOK
KEY>
• tags=<COMMA-SEPARATED TAG LIST>
For the URI attribute, make sure that the entire URI is percent-encoded.
Here are the invocation attributes that you use to launch a Remember card to add a file or URI to a new entry:
Attribute Value
Target ID sys.pim.remember.composer
Action bb.action.SHARE
URI file://
list://
http://
https://
{
"title": "Title to be set on
the entry"
}
{
"subject": "Webpage subject",
"description": "Webpage
description"
}
[
{ "uri": "file:///path/to/
video.mp4" },
{ "uri": "file:///path/to/
picture.jpg" }
]
MIME type For list:// URIs only, the MIME type must be
filelist/<TYPE>.
Editing an entry
Here are the invocation attributes that you use to launch a Remember card to edit an entry:
Action bb.action.EDIT
URI pim:application/
vnd.blackberry.notebookentry:<ACCOUNT
KEY>:<ENTRY KEY>
Viewing an entry
Here are the invocation attributes that you use to launch a Remember card to view an entry:
Attribute Value
Target ID sys.pim.remember.previewer
Action bb.action.VIEW
URI pim:application/
vnd.blackberry.notebookentry:<ACCOUNT
KEY>:<ENTRY KEY>
Opening an entry
Here are the invocation attributes that you use to launch a Remember card to open an entry:
Attribute Value
Target ID sys.pim.remember
Action bb.action.OPEN
Search
Here are the invocation attributes you use to search with keywords:
Attribute Value
Target ID sys.search
Action bb.action.OPEN
To display your app in the Extended Search section of the Search application, here's how you can specify your
app in the config.xml file:
<invoke-target id="com.xyz.test">
<invoke-target-type>APPLICATION</invoke-target-type>
<filter>
<action>bb.action.SEARCH.EXTENDED</action>
<mime-type>application/vnd.bb.search.criteria</mime-type>
</filter>
</invoke-target>
When your app is registered, the Search application displays your app in the Extended Search section using
your app’s name and icon. Your application recieves any search requests via invocation requests. The search
string is delivered in the data attribute of the request and is in UTF-8 format.
Here are the invocation attributes you use to open the notification settings card of an application:
Attribute Value
Target ID sys.settings.card
Action bb.action.OPEN
URI "settings://notification/application?
id=" + packageInfo.name()) (for example,
settings://notification/application?
id=com.foo.bar)
Here are the invocation attributes you use for the Settings card:
Attribute Value
Target ID sys.settings.card
Action bb.action.OPEN
Here's a list of URIs you can use to invoke different Settings cards:
settings://about/general
settings://about/hardware
settings://about/os
settings://about/network
settings://about/legal
settings://about/workspace
Accessibility settings://accessibility
Accounts settings://pim
settings://pim/defaultAccounts
settings://pim/createAccount
settings://pim/listAccounts
settings://pim/createAccountType?
type=<type> where type can be facebook,
twitter, linkedin, evernote, or
mail_contacts_calendar
settings://pim/showAccount?id=<id>
settings://pim/deleteAccount?id=<id>
settings://pim/EnrollmentProgress
settings://language/input
settings://language/keyboard
settings://language/spellcheck
settings://language/assistance
Location settings://location
Mobile Hotspot settings://mhs
Mobile Network settings://radio
Network Connections settings://networkconnections
NFC settings://nfc
Notification settings://notification
Password settings://password
Payment Options settings://payment
Screen Reader settings://screenreader
Search settings://search
Security settings://security
Sharing settings://sharing
Text Messages
Here are the invocation attributes that you use to launch the composer card for the Text Messages app with
specific body text and recipients:
Attribute Value
Target ID sys.pim.text_messaging.smsuri
Action bb.action.COMPOSE
body
This field represents the text contained in the body of
the text message.
send
This field should be set as a Boolean value. If the
value is set to true, the message is sent right away. If
the value is false, the composer remains on the
screen.
Here are the invocation attributes that you use to launch the composer card for the Text Messages app with a
recipient field set to a specified phone number:
Attribute Value
Target ID sys.pim.text_messaging.smsuri
You can perform the same invocation by using the following invocation attributes in your invocation request:
Attribute Value
Target ID sys.pim.text_messaging.smsuri
Action bb.action.SENDTEXT
Here are the invocation attributes you use to share an attachment with a recipient, using the Text Messages
app:
Attribute Value
Target ID sys.pim.text_messaging.sharemedia
Action bb.action.SHARE
URI list://
You can perform the same invocation by using the following invocation attributes in your invocation request:
Attribute Value
Target ID sys.pim.text_messaging.smsuri
Action bb.action.SENDTEXT
URI tel:5198887465
[
{
"uri": "file:///path/to/file"
},
All the invocation attributes related to the Twitter app require a Twitter account to be set up on the device.
Here are the invocation attributes you use to share text with Twitter:
Attribute Value
Target ID Twitter
Action bb.action.SHARE
text/plain
MIME type
data://
URI
Here are the invocation attributes you use to share a photo with Twitter:
Attribute Value
Target ID Twitter
Action bb.action.SHARE
file:///path/to/content.png
URI
Here are the invocation attributes you use to share a URL with Twitter:
Attribute Value
Target ID Twitter
Action bb.action.SHARE
http://, https://
URI
Here are the invocation attributes you use to open a Twitter profile:
Attribute Value
Target ID com.twitter.urihandler
Action bb.action.VIEW
URI twitter:connect:<twitter_profile_name
>
Here are the invocation attributes you use to search Twitter for relevant tweets containing a search term:
Attribute Value
Target ID com.twitter.urihandler
Action bb.action.VIEW
URI twitter:search:<search_term>
Video editor
The video editor allows the user to change the saturation, brightness, contrast, and audio volume of a video
clip. The video editor can also trim, crop, and rotate the video clip.
Editing a video
Here are the invocation attributes you use to invoke the video editor card:
Attribute Value
Target ID sys.video_editor.card
Action bb.action.EDIT
URI videoeditor:///path/to/content.mp4
MIME type video/mp4
When video editing is complete, the video editor returns the output path of the saved video file in the data
property of the CardDoneMessage. The video editor sets the reason property to Canceled or Saved.
Voice note
The voice note card allows the user to record a voice note and save it.
Here are the invocation attributes you use to invoke the voice note card:
Attribute Value
Target ID sys.apps.audiorecorder
Action bb.action.CAPTURE
The metadata of the voice note is specified by size and format attributes. The format attribute can be
specified in any of the file extensions listed above.
YouTube
Here are the invocation attributes you use to share a video with YouTube:
Attribute Value
Target ID Youtube
Action bb.action.SHARE
URI file:///path/to/content.mp4
File extensions .3gp, .
3gpp, .avi, .flv, .m2v, .mp4, .mov, .
webm, .wmv
Note: The descriptions below are provided by the app vendor, not BlackBerry.
Finance
Cashalyst
Use this invocation target to import and view Quicken(qfx) and ofx bank transaction files. QFX/OFX files can be
downloaded from your online bank website.
Attribute Value
Target type application
Target ID com.digicasa.cashalyst.import
Data description Invocation requires either a file:// with the full path to
the qfx/ofx file or a data://local with the complete
contents of the qfx/ofx file.
Anagrammatist EN
Invocation calls Anagrammatist EN app. This application provides some functions for the word games - like
checking if the provided word exists, seraching for anagrams, searching for all the possible words from the
given letters etc.
Attribute Value
Target type application
Target ID AnagrammatistEN591c82ab559936cc457d58
1de4df064
Action bb.action.SEARCH.EXTENDED
Ambience
Target ID ambience
Action bb.action.OPEN
Photo Effect
PhotoEffect
Attribute Value
Target type application
Target ID com.umang.PhotoEffect
Action bb.action.OPEN
URIs file://
File extensions png, jpg, jpeg
Productivity
Integrate 'ekkes Express Charts' as a Composer Card to define Charts on-the-go. There's a sample app at
Github HowTo do this: https://github.com/ekke/ekkesChartInvoker You can select from existing Charts or
define a new one. The image is a full-screen JPEG.
Attribute Value
Target type card.composer
Target ID org.ekkescorner.charts.chartimages
Action bb.action.SHARE
To register your application as a default application, you must specify bb.action.OPEN as the action and
specify either a MIME type and a URI or a MIME type and a file extension in the config.xml file.
For example, to register your app as the default app to open a specific URL (http://www.example.com), your
app must specify bb.action.OPEN as the action, http://www.example.com as the URI, and text/
html as the MIME type in the target filter section of the config.xml file.
Note: If you are registering for a URI or a file extension and do not have a specific MIME type to declare, you
should specify a wildcard character * for the MIME type.
BBM is an instant messaging program designed to allow BlackBerry device users to communicate with each
other. Since its introduction to the suite of core BlackBerry applications, BBM has quickly become one of the
most widely used applications on BlackBerry smartphones. Users do not need to sign into or out of BBM. As
long as their BlackBerry devices are connected to a wireless network, BBM can keep users connected to their
BBM contacts and groups.
The BBM SDK, used in conjunction with the BlackBerry WebWorks SDK, lets you use the same infrastructure
upon which BBM is built to communicate between instances of your app on multiple BlackBerry devices. For
Adding Features 185
example, in a chess game app, a BlackBerry device user could invite a BBM contact to play a game of chess,
and the moves could be communicated back and forth using the BBM platform.
You can access the same infrastructure that BBM, one of the most successful and widely used mobile social
platforms, is built upon. With the BBM SDK, you can develop apps that incorporate social features such as
peer-to-peer connections between BlackBerry devices, or integrated chats. There is no need to develop these
social features yourself, and no server-side development is required to support them.
The BBM platform provides support for the social aspects of your app, such as tracking which BlackBerry
devices your app is installed on, managing the connections between instances of your app, and proactively
discovering the contacts who have already installed the app.
A sticky application is one that users find useful, engaging, and use frequently. When you integrate BBM into
your app you can create a community where BlackBerry device users can get together, socialize, and
communicate. Adding this social aspect can help your app maintain its presence on BlackBerry devices and
help attract users.
When people like something, they want to share it with others. Because BlackBerry device users can
communicate with any or all of their BBM contacts from within an app, when you create a BBM connected
app, you have a built-in advertising system.
Users can not only encourage their contacts to download your app, they can actively invite them to do so by
sending an invitation that links directly to the application details page in the BlackBerry World storefront.
Install Java
The first thing you need to do is download and install the Java SE 6 update 37 or later (JDK or JRE, 32-bit or 64-
bit).
Note: The BBM server simulator does not support Java 7.
Next, you set up Java environment variables and unlimited strength encryption.
The Java Cryptography Extension (JCE) enables encryption by using a key size of greater than 128 bits.
Note: You must live in an eligible country to enable this functionality. You can find more information in the
readme.txt file contained in the following .zip file.
Before you can test your BBM connected app in the device simulator you need to install some software.
If you don't have a BlackBerry 10 device, you can download and install the BlackBerry 10 Device Simulator to
test your applications. The BBM server simulator is bundled with the BlackBerry 10 Device Simulator.
To test your BBM connected app in the BlackBerry 10 Device Simulator, you need to install at least two
instances of the device simulator in different locations on your hard disk, one for each instance of BBM. Learn
more about how to Run multiple device simulators with BBM.
After you install the device simulator and a virtual machine, you're ready to get started. The first thing you need
to do is start the BBM server simulator. The BBM server simulator enables communication between instances
of BBM.
Note: You need to run only one instance of the BBM server simulator.
Next, start the device simulator: in the BlackBerry 10 Simulator - <version> directory, double-click the
BlackBerry 10 Simulator shortcut.
Then, connect the device simulator to the controller. The controller allows the device simulator to connect to
the BBM server simulator.
Note: The IP address cannot be 127.0.0.1 or localhost, even if the BBM server simulator is running on the
same computer that hosts the device simulator.
3. Click Connect. You can see activity in the BBM server simulator console when the connection is successful.
Note: To shut down the BBM server simulator when you finish testing, in the BBM Server Simulator directory,
double-click the Shutdown BBM Server Simulator shortcut. After the simulator stops, type exit at the
command prompt to close the command window.
Note: You need to run only one instance of the BBM server simulator.
1. Start VMware.
2. Navigate to the directory where you installed the simulator and open the BlackBerry 10 Simulator -
<version> directory.
3. Select BlackBerry10Simulator.vmx and click Open to start the simulator.
4. Open the controllers directory and run controller.exe.
5. Change the default PIN of the simulator by following the instructions in Configuring the simulator.
Note: The IP address cannot be 127.0.0.1 or localhost, even if the BBM server simulator is running on the
same host computer as the device simulator.
12.Click Connect.
You'll see activity in the BBM server simulator console when the connection is successful.
13.In the device simulator, click the app that you want to run.
14.Repeat steps 1 to 13 for each additional instance of the simulator that you want to run.
The BlackBerry Messenger pre-production environment is a dedicated cluster of BBM services that provides
all of the functionality of the BBM Social Platform. The pre-production environment is ideal for building
internal, alpha, and beta versions of your BBM connected app. It provides you with an opportunity to test your
If your app, or app version, does not already exist in BlackBerry World, it is automatically placed in the pre-
production environment. The UUID that you provide acts as a unique identifier for your app that facilitates
monitoring for any adverse or unintended events (such as burstiness) in the traffic that is associated with your
app. Since the pre-production environment is intended for testing, while restricting traffic from your app in the
production environment, the following limitations apply:
Communication limitations
To prevent an application from using too much of the available bandwidth, the BlackBerry Messenger platform
limits the total volume of data that is transferred by a BBM connected application as follows:
• All messages and application data transferred over channel and session connections for all BBM
connected applications that are running on a BlackBerry device are collectively limited to a maximum data
transfer rate that is configured by the BBM server. If the total volume of data attributed to an application
threatens to exceed the maximum transfer rate, the BBM platform throttles data traffic for that application
to reduce the transfer rate to an acceptable level. File transfers sent from a BBM connected application are
not considered to be application data, and are therefore exempt from this limitation on the data transfer
rate.
• Data sent from a BBM connected application over a channel/session connection is limited to a maximum of
60 KB per transfer.
• File transfers from a BBM connected application are limited to a maximum of 6 MB per file.
• The maximum number of users in a connection is limited to 24.
UUID Guidelines
A Universally Unique Identifier (UUID), also known as a Globally Unique Identifier (GUID), is a unique, 128-bit,
36-character identifier that you generate for your app using a UUID/GUID generator. Your app must provide a
UUID when it registers with the BBM social platform to access the social platform APIs. The UUID string must
conform to the Microsoft 8-4-4-4-12 format (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx). Valid characters consist of
hexadecimal values in the ranges 0 to 9 and a to f.
The UUID is also used to identify your app (along with the vendor name and the app name) in the pre-
production test environment, before the app is made available in BlackBerry World. If the app is installed from
BlackBerry World, the UUID is not used to identify it. You should use the same UUID when testing future
releases of the same app. If the UUID changes across versions, different versions of the same app will not be
able to communicate with each other in the pre-production environment.
If you have separate, optimized versions of your app for BlackBerry smartphones running BlackBerry 7 (or
earlier) and BlackBerry 10, there are some things you need to consider when adding BBM connected apps to
the vendor portal. Typically, you assign a separate SKU to each app that you add to the vendor portal.
However, if you want your app to be able to communicate across platforms, you must assign the same SKU to
each variant of your app. To have a BBM connected app that is running on a BlackBerry 7 smartphone
communicate with the same app running on a BlackBerry 10 smartphone, they must both have the same SKU
in BlackBerry World. You can still submit different screen shots, icons, feature image, descriptions, and
keywords for each variant of your app when using the same SKU. You can learn more about Adding and
managing apps on the BlackBerry World vendor portal website.
Payment Service
After you create an awesome app, you might want to offer in-app purchases. The Payment Service lets you do
just that. To get started, you need to include the Payment Service classes into your app. Then you can add your
app on the vendor portal for the BlackBerry World storefront. You can add digital goods to your app, offer
subscriptions, and charge for additional features. Learn more about getting your app up for sale on BlackBerry
World.
You can use your imagination to decide what digital goods to create, and how best to offer them for sale from
within your app. For example, you can:
• Sell guides to help users learn about levels, back doors, and bonus points.
• Offer additional levels or new characters in your game.
• Upgrade your users to the advanced version of your app.
• Sell extra services, such as music or video streaming in your app.
• Offer items such as eBooks, personalized greeting cards, photos, and maps.
• Sell subscriptions to renewable goods, such as magazines and newsletters.
You can incorporate the Payment Service in your app and then upload the app and its digital goods, along with
pricing and a description to the BlackBerry World vendor portal. The Payment Service manages all the
technical and financial details for you. You don't have to waste time managing relationships or business terms
with payment providers and coding for integration into each provider's solution.
The Payment Service provides a fast and familiar purchase experience for your users. Using their BlackBerry
ID, users can apply various payment methods, including credit card, PayPal, and carrier billing, toward the
purchase of digital goods you define—all without leaving your app.
All the Payment Service functions are designed to make the user experience consistent for each type of
payment and for every BlackBerry device. When a user wants to use your app to purchase digital goods, this is
what happens:
Component Description
Payment Service server The Payment Service server is the part of BlackBerry
World that facilitates interactions between your app,
the payment providers, the vendor portal, and your
content server.
What's next?
Let's get started earning some money! Register your digital goods, learn about what the Payment Service has
to offer, and use the code samples to create an app that includes some in-app purchasing.
Initial trial period If you decide to offer digital goods as 7-day or 30-day
subscriptions, you can set an initial trial period for the
subscription.
Price You can specify a price for your digital goods from a
list of pricing tiers that BlackBerry World provides. For
subscription-based digital goods, the price that you
Learn more about submitting applications and digital goods on the BlackBerry World vendor portal.
If, however, you host your digital goods on a content server and deliver them to BlackBerry devices over the
wireless network, you can update and add to your offering of digital goods without having to submit a new
release of your application to the BlackBerry World storefront.
There are two ways to keep your content server up to date on successful purchases: design your application to
send a notification to the content server, or request a notification from the Payment Service.
To request notifications from the Payment Service, you must set up a dynamic license model when you register
the digital goods in the BlackBerry World vendor portal.
The dynamic license model for digital goods requires an HTTPS URL for your content server. During each
successful purchase, the Payment Service server sends your content server a request for a license key, and
the following purchase parameters:
Your content server needs to respond to the Payment Service server with a license key, which is then passed to
the user's device as part of the purchase transaction.
Initiating a purchase
You can initiate a purchase in your app by calling the purchase method.
When a user starts a purchase transaction, the blackberry.payment.purchase function is called. When
the user finishes interacting with the device to engage the payment process, the app receives a response.
When the blackberry.payment.purchase function is called, only the ID or SKU of the digital good to be
purchased is required; you don't need to provide both. If you do provide both, the ID takes precedence.
function purchase() {
alert("Trying to call purchase");
blackberry.payment.developmentMode = true;
try {
blackberry.payment.purchase({
"digitalGoodID": "16823864",
"digitalGoodSKU": "BB10-CG-02",
The Payment Service SDK for BlackBerry WebWorks includes metaData property. You can use this property
to provide extra information that remains associated with the purchased good. For example, if a book vendor
offers multiple titles at a single price point and represents them on the vendor portal as a single digital good,
when a book is purchased, the vendor could set the metaData value as the ISBN for that book. Then, if the
user checks past purchases, the metaData property can be used to differentiate between past book
purchases.
By default, users see the app name and the icon that you registered with BlackBerry World when they interact
with purchase dialog banners. If you want users to see a customized name and icon on the purchase dialog
banners when they purchase your app, you can set the purchaseAppName and purchaseAppIcon
properties.
Using the purchaseAppName and purchaseAppIcon properties can be a good solution if you offer digital
goods with a single name and price point. For example, if you sell additional levels of a game at a single price
point, you can use a generic digital good called "My game level" for all such levels. When a user makes a
purchase, the game app should override "My game level" with the name of the level that the user purchased
(using the purchaseAppName property). This approach makes sure that the user is aware of exactly what
they are purchasing on the purchase confirmation screen.
If you use the purchaseAppIcon property, you can supply an icon in any standard format set to ?
height=100for a 100 x 100 size.
<script type="text/javascript">
function purchase() {
try {
blackberry.payment.purchase({
"digitalGoodID":"123",
"digitalGoodSKU":"someSKU",
"digitalGoodName":"SomeName",
"metaData":"metadata",
"purchaseAppName":"WebWorks APP",
"purchaseAppIcon":null,
"extraParameters": {
"key1": "value1",
"key2": "value2"
}
Responding to a purchase
When the purchase process completes, your app calls either onSuccess if the purchase is successful, or
onFailure if the purchase is not successful.
<script type="text/javascript">
function purchase() {
try {
blackberry.payment.purchase({
"digitalGoodID":"123",
"digitalGoodSKU":"someSKU",
"digitalGoodName":"SomeName",
"metaData":"metadata",
"purchaseAppName":"WebWorks APP",
"purchaseAppIcon":null,
"extraParameters": {
"key1": "value1",
"key2": "value2"
}
},
onSuccess, onFailure);
} catch (e) {
alert ("Error" + e);
}
}
function onSuccess(purchasedItem) {
var transId = purchasedItem.transactionID;
var sku = purchasedItem.digitalGoodSKU;
var dgId = purchasedItem.digitalGoodID;
alert("Purchased Item: " + transId + "," + sku + "," + dgId);
}
function onFailure(error) {
alert("Error occurred: " + error.errorText + ", " + error.errorID);
}
</script>
The paymentError object is returned as a parameter for callbackOnFailure if the purchase process is
unsuccessful. The paymentError object has two properties: Number errorID and an errorText string.
Number errorID
String errorText
The paymentError object returns a text string that can display as a readable message for the user.
You can avoid offering a digital good to a user who has already purchased it by checking the user's purchase
history with the blackberry.payment.getExistingPurchases function.
You can also use the blackberry.payment.getExistingPurchases function when a user initiates a
request to cancel a subscription, in order to obtain a purchase ID for the cancellation process.
If the transaction is successful, the onSuccess callback function returns a purchase object for each purchase
of the app, made by the user.
<script type="text/javascript">
function getExistingPurchases() {
try {
blackberry.payment.getExistingPurchases(true, onSuccess,
onFailure);
} catch (e) {
alert ("Error" + e);
}
}
function onSuccess(purchases) {
for (var i = 0; i < purchases.length; i++) {
var transId = purchases[i].transactionID;
var sku = purchases[i].digitalGoodSKU;
var dgId = purchases[i].digitalGoodID;
alert("Purchased Item " + i + ": " + transId + "," + sku + "," +
dgId);
}
}
function onFailure(err) {
alert("Error occurred: " + err.errorText + ", " + err.errorID);
Managing a subscription
You can use the following functions in the Payment Service for BlackBerry WebWorks to manage subscriptions
in your app.
Subscriptions can be referred to as app-level subscriptions or digital goods-level subscriptions. When you add
your app to BlackBerry World you can select Subscription as the license type for your app. If you add a digital
good to your app, you can select Subscription as the license type for your in-app digital good.
When a user tries to access an app-level subscription, the Payment Service calls
blackberry.payment.checkAppSubscription to verify that the user has rights to the subscription.
If the transaction is successful and the user's BlackBerry ID matches a currently active subscription to the
app, the Payment Service returns the onSuccess function with the parameter
data.subscriptionExists set to True. If no match is made, then data.subscriptionExists is set
to False.
If the transaction is not successfully completed, the Payment Service returns the onFailure function with a
PaymentError object.
<script type="text/javascript">
function checkAppSubscription() {
try {
blackberry.payment.checkAppSubscription(onSuccess, onFailure);
} catch (e){
alert("Error" + e);
}
}
function onSuccess(data) {
alert("User is " + (data.subscriptionExists ? "" : "not ") +
"subscribed to the app.");
}
function onFailure(error) {
alert("Error occurred: " + error.errorText + ", " + error.errorID);
}
</script>
When a user tries to access a digital goods subscription, the Payment Service calls
blackberry.payment.checkExisting to verify that the user has rights to the subscription. The function
includes information to describe the digital good: id for the identifier assigned by BlackBerry World or sku for
the SKU of the digital good. If both arguments are included in the transaction, id takes precedence and sku is
ignored.
If the BlackBerry ID associated with the transaction is subscribed to the digital good, the Payment Service
returns the onSuccess function with the parameter data.subscriptionExists set to True. If the
transaction is successful, but no match is made, then data.subscriptionExists is set to False.
If the transaction is not successfully completed, the Payment Service returns the onFailure function with a
PaymentError object.
<script type="text/javascript">
function checkSubscription() {
try {
blackberry.payment.checkExisting({
"id": 12345"
}, onSuccess, onFailure);
} catch (e) {
alert ("Error" + e);
}
}
function onSuccess(data) {
alert("User is " + (data.subscriptionExists ? "" : "not ") +
"subscribed to the item.");
}
function onFailure(error) {
alert("Error occurred: " + error.errorText + ", " + error.errorID);
}
</script>
Canceling a subscription
A user can only cancel a subscription for a digital good; cancellation of other types of purchases (license types)
are not supported. A purchase ID is required in order to identify the subscription that a user wants to cancel, so
when a user makes a request to cancel a subscription, your app calls a getExistingPurchases function
first. A successful getExistingPurchases function returns the purchase ID so that the cancellation can
be completed.
Note: If a user successfully cancels a subscription, the subscription remains valid until the end of the current
subscription period. For example, if the user has paid for a subscription to December 31st, and cancels the
subscription on December 15th, the subscription remains valid until the paid period expires on December
31st.
function cancelSub() {
try {
blackberry.payment.cancelSubscription("18722506",
onCancelSubSuccess, onCancelSubError);
} catch (e) {
alert("cancelSubscription exception");
console.log(e);
}
}
function onCancelSubSuccess(data) {
console.log(data);
alert("Cancellation " + (data.subscriptionCancelled ? "" : "NOT ") +
"successful");
}
function onCancelSubError(error) {
console.log(error);
alert("Error occurred: " + error.errorText + ", " + error.errorID);
You can use development mode to test your logic for retrieving past purchases using purchase data for
transactions made in the current session. This is a great initial testing step for any application that sells digital
goods.
When you add new digital goods to the BlackBerry World vendor portal you can test them while they are still in
a Draft status using a sandbox user account. This is a great method for testing the purchase of your digital
goods in a way that is very close to the end-user experience.
When you use a sandbox user account to purchase digital goods from BlackBerry World, you are not charged
for the purchase. If you use the sandbox user account to purchase the goods or apps of another vendor,
however, you will be charged for the purchase.
To create a sandbox user account, you need to have a BlackBerry World vendor portal membership and sign in
with an Admin level user account.
To test the purchase of your digital goods with a sandbox user account:
1. Sign in to the BlackBerry World vendor portal with a user account that has Admin level priviledges, and
click Sandbox from the left pane.
2. Click Add New User and complete the form using a BlackBerry ID.
3. Add digital goods to a new or existing app that has been added to the vendor portal.
4. Enable Development Mode on your device by navigating to Settings > Security and Privacy > Development
Mode and enabling the Use Development Mode toggle button.
5. Start BlackBerry World on your device and swipe down from the top bezel to display the application menu.
Tap Settings > Development Mode, then enter the ID or SKU of your app and tap Load to download your
app.
Adding Features 205
Note: This Development Mode screen, where you can enter the ID of your application and download it right
from your vendor account, will be visible only if your device is in Development Mode.
Here are some things to consider when you use the BlackBerry World vendor portal to test your in-app digital
goods:
• Make sure the connection mode in your app is set to Production so that your test purchases go through the
BlackBerry World server.
• Apps that are in draft can only be downloaded from BlackBerry World when you are using a sandbox user
account (any other kind of user account won't work).
• You can only retrieve past purchases for the current test session. Digital goods that are purchased in a draft
status are not written to the transaction database, so when you end the test session the cache is cleared.
• You can test purchasing an app only from a physical device, not from the BlackBerry 10 Device Simulator.
• BlackBerry World has a cache, so there may be a delay before your new digital goods are accessible from
BlackBerry World on your device.
• You can use a sandbox user account to purchase your own apps and digital goods that are approved and
for sale on the BlackBerry World storefront without being charged.
• You don't need to remove an existing app from sale on the BlackBerry World storefront to add new digital
goods in draft status, and test them with a sandbox user account.
• If you add a new app (meta data) and digital goods to the BlackBerry World vendor portal, you must also
add a release (application data) in order to test the download and purchase of the digital goods.
The information below can help you develop a push-enabled app using BlackBerry WebWorks.
For information about developing a Push Initiator to use with your push-enabled app, see Push Service.
Architecture
The architecture diagram shows a complete Push Service solution that includes the server-side library and the
client-side library. The libraries work together to deliver content from the Push Initiator to a push-enabled
application.
Component Description
Push The Push Initiator is the application that creates request messages (such as a push request,
Initiator cancel request, or status-query request) and response messages (such as a result-notification
response) using the server-side library and submits them to the push proxy gateway (PPG). The
Push Initiator also uses the server-side library to process subscription-related requests that it
receives from the push-enabled application on the BlackBerry device.
Server-side You can use the Push Service SDK as the server-side library or you can provide your own library.
library If you use the Push Service SDK, the server-side library provides the Java APIs that the Push
Initiator uses to interact with the PPG. The Push Initiator also uses the server-side library to
process subscription-related requests that it receives from the push-enabled application on the
device. For information about developing a Push Initiator using the Push Service SDK, see the
Push Service SDK documentation.
Push Proxy The PPG processes push request messages and status-query messages that it receives from
Gateway the Push Initiator. After the PPG processes a push request message, it sends a response
message that communicates the overall outcome of the push message. The response message
contains a result code or a PAP error code.
Client-side The BlackBerry 10 WebWorks SDK contains the client-side library. The client-side library
library provides the JavaScript APIs that the push-enabled application uses to create a PushService
object, create and destroy a channel, and receive push messages.
Push- The push-enabled application runs on a device, and might send subscription-related requests
enabled to the Push Initiator. The push-enabled application uses the client-side library to create a
application PushService object, create and destroy a channel, and receive push messages.
Levels of service
When you use the Push Service, you can choose from two levels of service: Push Essentials and Push Plus. The
majority of push-enabled apps in BlackBerry World use Push Essentials.
If you are pushing data through the BlackBerry Enterprise Service, you have access to features comparable to
Push Plus.
Push Essentials
When you use the Push Essentials level of service, you can send content to a device, but you can't query
the status of the content or receive acknowledgments after you send the content. However, you can set
the expiry time for content delivery for up to 30 days.
Here's how content is sent to a client application on a BlackBerry device with the Push Essentials level of
service.
Push Plus
Push Plus is a paid level of service. It offers the following additional functionality so that you can check
the status and receive notifications about delivered content:
• Results notification lets you know when messages are delivered, if they couldn't be delivered, or if
they expired waiting to be delivered.
• The PPG keeps track of the current status of a push message, and you can use a status query to
check the status. The status of a push message can be pending, delivered, undeliverable, or expired.
• Push cancellation can withdraw messages if they haven't been delivered already.
• You can set the expiry time for content delivery for up to 8 hours.
Here's how content is sent to a client application on a BlackBerry device with the Push Plus level of
service.
Requirements
Push Initiator To test your push-enabled app, you need a Push Initiator. To develop the
Push Initiator, you can use our Push Service SDK or another library of your
choice. The Push Service SDK includes two sample Push Initiators that you
may be able to use to test your push-enabled app.
The application ID and PPG You get this information by email when you register your Push Initiator with
URL for your Push Initiator BlackBerry. For more information about registering your Push Initiator, see
Push Service and the Push Service Evaluation Form.
If you are using the push technology of the BlackBerry Enterprise Service
only, you don't need to register.
Before you can use the Push Service APIs with your application, you need to add the following plugins to your
project:
• com.blackberry.push
• com.blackberry.invoked
Adding a plugin copies the plugin to your project's plugins folder, and makes the APIs available to your
application. It also adds the required <feature> element to your application's config.xml file. After you add a
plugin, the contents of the plugin are packaged together with your other application resources the next time
you build your application. To add the plugins:
Before you can use the Push Service APIs with your application, you need to update your application's
config.xml file with the following statements.
1. Add an entry for the invoke events that your application receives for push messages.
Note the value for the invoke-target id. This value must match the invokeTargetID that's passed
into the call to the PushService.create() function. For more information about the
invokeTargetID and PushService.create(), see Creating a PushService object.
Also note that the action tag is set to bb.action.PUSH. This value indicates that the invoke relates
specifically to push messages. The event listener in the sample application also uses this value to check
that the invoke event is a push message. For more information about the event listener and the push invoke
event, see Receiving a push message.
2. To allow your app to be opened from BlackBerry Hub notifications, add the following statements.
Note that the action tag is set to bb.action.OPEN. This value indicates that the invoke relates to an
open invoke event. In the sample application, an open invoke event occurs when a user taps a notification
for a push message in the BlackBerry Hub. The event listener in the sample application also uses this value
to check that the invoke event is an open invoke event. For more information about the event listener and
the open invoke event, see Handling notifications in the BlackBerry Hub.
The sample app accepts push messages with the following types of content. If you're using the Push Service
SDK to develop a Push Initiator, the API automatically specifies the type of content in the header of the push
message. Using the Push Service, a Push Initiator can send up to 8 KB of any type of content (images, text, or
audio).
To test the sample app on a device, you need to have a Push Initiator running. The Push Service SDK includes
sample Push Initiators.If you implement a Push Initiator that doesn't use the Push Service SDK, or your Push
Initiator only uses the low-level APIs without subscription support from the SDK, you can still use the sample
app for testing purposes. You need to indicate that you are not going to subscribe with the Push Service SDK
when you configure the sample app. For details, see Configure the sample app.
To download the sample app, visit the samples repository. The repository contains the source code and
associated files for the app. The README.md file in the repository contains the instructions that you need to
build and deploy the sample app on a BlackBerry device.
Folder Description
Images This folder contains the images for the sample app.
Scripts This folder contains the JavaScript files for the sample app.
Styles This folder contains the CSS files for the sample app.
When you run the sample push-enabled app for the first time, you need to specify some configuration
information, including the information from the confirmation email message that you received when you
registered your Push Initiator to use the Push Service. When you develop your own app, you can hard code this
2. Click Public/BIS if you're using the Push Service without the BlackBerry Enterprise Service or
Enterprise/BDS if you're pushing data through the BlackBerry Enterprise Service.
3. Clear the Subscribe with Push Service SDK check box if one of the following is true:
• Type the application ID that is specified in the confirmation email message that you received from
BlackBerry.
• If you're pushing data through the BlackBerry Enterprise Service, type a unique application ID of your
choosing. If you clear the Subscribe with Push Service SDK check box, you can't type an application
ID. In this case, the Push Service APIs create an application ID for you automatically.
After you configure the sample push-enabled app, you need to register the app to create a push channel to the
PPG to receive push messages.
If you chose to subscribe with the Push Service SDK when you configured the sample app, the Push Initiator
requires a username and password that it authenticates before allowing the subscription. The sample app
provides a Register dialog box where you can type any username and password.
To see the code that creates the channel and handles the subscription, see Creating a push channel.
2. If you chose to subscribe with the Push Service SDK, type any username and password in the Register
screen.
The sample application calls the static PushService.create() function to create a PushService object
to perform push-related operations. Once the PushService object is instantiated, the sample application
can make calls to the object to receive and process push messages.
In your application, you need to call PushService.create() with one appID parameter and one
invokeTargetID parameter. If you try to create another PushService object with a different appID or
invokeTargetID parameter, the create operation fails with an exception.
The appID parameter corresponds to the application ID that you specified when you configured the sample
application. For details about configuring the sample application, see Configure the sample application.
The invokeTargetID is a value that you generate. The value identifies the push-enabled application that's
the target of a push message, and that's invoked when a push message arrives. The value must be the same in
the config.xml file for your application and in the PushService.create() function. For more
information about updating your config.xml file, see Update your config.xml file.
Call PushService.create()
The static PushService.create() function instantiates a PushService object. If the object is created
successfully, the create function calls the successCreatePushService() callback function with the
PushService object that the application can use. If the object isn't created, the create function calls the
failCreatePushService() callback function with a result number value. The result corresponds to
one of the error constants provided in the PushService class. For more information about the error
constants, see the PushService class in the API Reference.
The call to PushService.create() is different depending on whether or not the Push Service is used with
the BlackBerry Enterprise Service. If the Push Service is not used with the BlackBerry Enterprise Service, the
create function call looks like this:
var ops;
if (sample.pushcapture.usingpublicppg) {
// Consumer application using public push
ops = { invokeTargetId : sample.pushcapture.invokeTargetIdPush,
appId : sample.pushcapture.appid,
ppgUrl : sample.pushcapture.ppgurl
};
} else {
// Enterprise application using enterprise push
.
.
.
}
blackberry.push.PushService.create(ops,
sample.pushcapture.successCreatePushService,
sample.pushcapture.failCreatePushService,
If the Push Service is used with the BlackBerry Enterprise Service, the create function call looks like this:
var ops;
if (sample.pushcapture.usingpublicppg) {
// Consumer application using public push
.
.
.
} else {
// Enterprise application using enterprise push
if (sample.pushcapture.usesdkaspi) {
// If we're using the Push Service SDK for our Push
// Initiator implementation, we will have specified
// our own application ID to use.
ops = { invokeTargetId :
sample.pushcapture.invokeTargetIdPush,
appId : sample.pushcapture.appid
};
} else {
ops = { invokeTargetId :
sample.pushcapture.invokeTargetIdPush };
}
}
blackberry.push.PushService.create(ops,
sample.pushcapture.successCreatePushService,
sample.pushcapture.failCreatePushService,
sample.pushcapture.onSimChange,
sample.pushcapture.onPushTransportReady);
Call successCreatePushService()
PushCapture.prototype.successCreatePushService = function(service) {
The failCreatePushService() callback function shows the error handling if the PushService object
isn't created, and the error messages that you can use for debugging. In your application, you might want to
handle the errors differently. For example, you might want to retry an operation first before displaying an error
message. The API Reference lists the possible actions that you can take for each error constant. The API
Reference also tells you which error codes apply to which function calls.
PushCapture.prototype.failCreatePushService = function(result) {
.
.
.
if (result == blackberry.push.PushService.INTERNAL_ERROR) {
alert("Error: An internal error occurred while calling " +
"blackberry.push.PushService.create. Try restarting the
application.");
} else if (result == blackberry.push.PushService.
INVALID_PROVIDER_APPLICATION_ID) {
// This error only applies to consumer applications that use
// a public/BIS PPG
alert("Error: Called blackberry.push.PushService.create with
a missing " + "or invalid appId value. It usually means a
programming error.");
} else if (result == blackberry.push.PushService.
MISSING_INVOKE_TARGET_ID) {
alert("Error: Called blackberry.push.PushService.create with
a missing " + "invokeTargetId value. It usually means a
programming error.");
} else if (result ==
blackberry.push.PushService.SESSION_ALREADY_EXISTS) {
alert("Error: Called blackberry.push.PushService.create with an
appId or " + "invokeTargetId value that matches another
application. It usually means a " + "programming error.");
} else {
alert("Error: Received error code (" + result + ") after " +
"calling blackberry.push.PushService.create.");
}
};
You can use the Push Service APIs to start running your application when a push message arrives, and to
continue running it in the background. This saves valuable device resources because your application doesn’t
have to be running all the time to receive push messages.
The sample application calls the launchApplicationOnPush() function with a value of true. This call
registers the application so that it starts running in the background if it isn't already running when a push
message arrives. If you don't want to register your application so that it starts running in the background when
a push message arrives, you can call launchApplicationOnPush() with a value of false. The push
PushCapture.prototype.successCreatePushService = function(service) {
.
.
.
sample.pushcapture.pushService.launchApplicationOnPush(
sample.pushcapture.launchapp,
sample.pushcapture.launchApplicationCallback);
};
The launchApplicationCallback() callback function shows the error handling if the launch operation
fails, and the error messages that you can use for debugging. In your application, you might want to handle the
errors differently. For example, you might want to retry an operation first before displaying an error message.
The API Reference lists the possible actions that you can take for each error constant. The API Reference also
tells you which error codes apply to which function calls.
if (result == blackberry.push.PushService.SUCCESS) {
// Successfully registered to launch
.
.
.
} else {
.
.
.
if (result == blackberry.push.PushService.INTERNAL_ERROR) {
alert("Error: An internal error occurred while calling
launchApplicationOnPush. " + "Try restarting the
application.");
} else if (result == blackberry.push.PushService.
CREATE_SESSION_NOT_DONE) {
alert("Error: Called launchApplicationOnPush without an " +
"existing session. It usually means a programming error.");
} else {
alert("Error: Received error code (" + result + ") after "
+ "calling launchApplicationOnPush.");
}
}
};
The sample application creates a push channel to the PPG to receive push messages. The application only
needs to create a channel the first time it starts, or if a destroy channel occurred previously, and you want to
start receiving push messages again.
You can open the Register screen by tapping Register at the bottom of the device screen. The Register screen
appears.
After you type the username and password, and tap Submit, the sample application tries to create a channel.
If you're not subscribing with the Push Service SDK, you don't need to provide a username and password. You
can simply tap Register and Submit, and the sample application tries to create a channel.
Call createChannel()
The sample application calls createChannel() to create a channel to the PPG. The createChannel()
function includes the createChannelCallback callback function as an argument. If the channel creation
is successful, createChannelCallback returns a token that isn't null. The token represents the device and
the application that receives push messages. You need to communicate the token to the Push Initiator so that
the Push Initiator can use the token to send push messages to the application. If the channel creation fails, the
token is null, and you should ignore it.
sample.pushcapture.pushService.createChannel(
sample.pushcapture.createChannelCallback);
The createChannelCallback callback function shows the error handling if the create channel operation
fails. In your application, you might want to handle the errors differently. For example, you might want to retry
an operation first before displaying an error message. The API Reference lists the possible actions that you can
take for each error constant. The API Reference also shows which error codes apply to which function calls.
sample.pushcapture.constructor.prototype.createChannelCallback =
function(result, token) {
if (result == blackberry.push.PushService.SUCCESS) {
// Success! Communicate the token to the Push Initiator.
} else {
.
.
.
// Error handling
}
};
If the channel creation is successful, and you're subscribing with the Push Service SDK, the sample
application calls subscribeToPushInitiator() to subscribe with the Push Initiator. The subscribe
function passes in the token to the Push Initiator and the username and password that you typed on the
Register screen. If you're not subscribing with the Push Service SDK, the sample application doesn't call
subscribeToPushInitiator().
sample.pushcapture.constructor.prototype.subscribeToPushInitiator =
function(token) {
document.getElementById("progressinfo").innerHTML
= "Subscribing to Push Initiator...";
var type;
if (sample.pushcapture.usingpublicppg) {
type = "public";
} else {
type = "bds";
}
xmlHttp.open("GET", subscribeUrl);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
var status = xmlHttp.status;
var returnCode = xmlHttp.responseText;
sample.pushcapture.pushInitiatorSubscribeHandler(status,
returnCode);
}
};
The sample application registers an event listener that listens for invoke events. The invoke event can be a
push invoke event or an open invoke event. A push invoke event occurs when the application receives a push
message. An open invoke event occurs when a user taps a notification for a push message in the BlackBerry
Hub. The following code sample shows you how the sample application handles a push invoke event. To see
how the sample application handles an open invoke event, see Handling notifications in the BlackBerry Hub.
The onInvoke() function first checks the action property of the invokeRequest to see if it matches the
string value bb.action.PUSH. The function then calls extractPushPayload() which returns a
PushPayload object. The application processes the PushPayload object by calling
pushNotificationHandler(). In your application, you can provide the code to process the push
message in a way that's appropriate for your environment.
PushCapture.prototype.onInvoke = function(invokeRequest) {
if (invokeRequest.action != null && invokeRequest.action ==
"bb.action.PUSH") {
var pushPayload = sample.pushcapture.pushService.
extractPushPayload(invokeRequest);
sample.pushcapture.pushNotificationHandler(pushPayload);
} else if (invokeRequest.action != null && invokeRequest.action ==
"bb.action.OPEN") {
.
.
.
}
};
The push message is stored in the data field of the PushPayload object. The type of the data field is Blob.
You need to convert the push message from a Blob object to a format that you can work with. The API
Reference shows you how to convert the Blob object to binary data and plain text.
The Push Initiator can send a confirmed push message with application-level reliability. The push-enabled
application must acknowledge a confirmed push message. The push-enabled application can determine if it
received a confirmed push message by checking the Boolean field isAcknowledgeRequired from the
PushPayload object. If the property is set to true, the push-enabled application must acknowledge the
push message by either accepting it by calling pushpayload.acknowledge(true) or rejecting it by
calling pushpayload.acknowledge(false). For more information about these functions, see the API
Reference.
If you register your application to start running in the background when a push message arrives using the
launchApplicationOnPush() function, your application continues to run after it processes the message.
This can use up device resources, so it's a good practice to exit your application after it processes a push
message. You have to be careful, however, not to exit your application if it was ever displayed full screen (in the
foreground) because the user might still be using your application.
To exit after processing a push message, the sample application creates the hasBeenInForeground
boolean variable to check whether the application was ever displayed full screen. The variable is set initially to
false.
/**
* Boolean indicating whether the application has ever been in the
* foreground. This boolean is used to determine whether we are
* dealing with the situation where the application is set to launch
* on a new push, the application is currently not running, and a new
* push comes in. The application will be launched in the background
* to process the push. If the user does not bring the app to the
* foreground while we are processing the push, then we exit
The sample application checks the current window state when it starts to see if it starts full screen. If it does,
the application sets the hasBeenInForeground variable to true. The application also listens for the
resume event. If this event occurs, the application was displayed full screen by the user, and the
hasBeenInForeground variable is set to true.
PushCapture.prototype.initPushService = function() {
// Check if the application started up in the foreground.
// We are trying to determine if the application was launched in
// the background and so we would be able to process a push and
// exit from the application.
if (blackberry.app.windowState == "fullscreen") {
sample.pushcapture.hasBeenInForeground = true;
}
.
.
.
};
PushCapture.prototype.onResume = function() {
sample.pushcapture.hasBeenInForeground = true;
};
After the sample application processes the push message, it checks the hasBeenInForeground variable. If
the variable is true, the application doesn't exit. If the variable is false, the application was never displayed
full screen. The application started in the background when a push message arrived, and can exit after it
processes the message.
The sample application handles notifications of push messages in the BlackBerry Hub in the following ways:
• When a user taps on a notification in the BlackBerry Hub, the sample application receives an open invoke
event, and displays the push message that corresponds to the notification.
• When the sample application receives a push message, it adds a notification to the BlackBerry Hub.
• When a user taps on the push message in the sample application, the application removes the notification
from the BlackBerry Hub.
• When a user deletes an individual push message in the sample application, the application removes the
notification for the push message from the BlackBerry Hub.
• When a user taps Mark All Open or Delete All in the sample application, the application removes all the
notifications for the sample application from the BlackBerry Hub.
The sample application registers an event listener that listens for invoke events. An open invoke event occurs
when a user taps a notification for a push message in the BlackBerry Hub.
The onInvoke() function first checks the action property of the invokeRequest to see if it matches the
string value bb.action.OPEN. If the property matches the string value, the user tapped a notification in the
BlackBerry Hub. The sample application displays the push message that corresponds to the notification.
if (sample.pushcapture.isDomReady) {
if (document.getElementById("push-list") == null) {
// We are not on the home screen.
// Pop off the current screen so that the push can
// be opened properly.
bb.popScreen();
To add a notification for the sample application to the BlackBerry Hub, the sample application creates a
Notification object.
Notice that targetAction matches the bb.action.OPEN action in the config.xml file. The
sample.pushcapture.invokeTargetIdOpen constant has a value of
sample.pushcapture.invoke.open which matches the invoke-target id in the config.xml file.
For more information about the config.xml file, see Update your config.xml file. Additionally, when you
create a notification, you need to encode the payload that you specify in Base64.
To remove a notification for the sample application from the BlackBerry Hub, the sample application calls
Notification.remove(), and passes in the sequence number of the push message that needs to be
removed. This code is called when the user taps the trash can icon next to a push message in the sample
Notification.remove(sample.pushcapture.selectedPushSeqnum +
sample.pushcapture.notificationSuffix);
To remove all the notifications for the sample application from the BlackBerry Hub, the sample application
calls Notification.remove() with the sequence number of each push message in the sample
application. This code is called when the user taps either Mark All Open or Delete All in the sample application.
The sample application destroys the push channel to the PPG to stop receiving push messages.
If you chose to subscribe with the Push Service SDK when you configured the sample application, the Push
Initiator requires a username and password that it authenticates before unsubscribing. The sample application
provides an Unregister screen where the user can type any username and password. For your application,
check with your push content provider to get a valid username and password.
You can open the Unregister screen box by tapping Unregister at the bottom of the device screen. The
Unregister screen appears with the currently registered user's name and password.
After you tap Submit, the sample application tries to destroy the channel.
If you're not subscribing with the Push Service SDK as the Push Initiator, you don't need to provide a username
and password. You can tap Unregister and Submit, and the sample application tries to destroy the channel.
The sample application calls destroyChannel() to destroy the channel to the PPG. The
destroyChannel() function includes the destroyChannelCallback callback function as an argument.
sample.pushcapture.pushService.destroyChannel(
sample.pushcapture.destroyChannelCallback);
The destroyChannelCallback callback function shows the error handling if the destroy channel
operation fails. In your application, you might want to handle the errors differently. For example, you might
want to retry an operation first before displaying an error message. The API Reference lists the possible actions
that you can take for each error constant. The API Reference also shows which error codes apply to which
function calls.
sample.pushcapture.constructor.prototype.destroyChannelCallback =
function(result) {
if (result == blackberry.push.PushService.SUCCESS ||
result == blackberry.push.PushService.
CHANNEL_ALREADY_DESTROYED ||
result == blackberry.push.PushService.
CHANNEL_ALREADY_DESTROYED_BY_PROVIDER ||
result == blackberry.push.PushService.
CHANNEL_SUSPENDED_BY_PROVIDER ||
result == blackberry.push.PushService.
PPG_SUBSCRIBER_NOT_FOUND ||
result == blackberry.push.PushService.
CREATE_CHANNEL_NOT_DONE) {
// Success!
} else {
.
.
.
// Error handling
}
};
Call unsubscribeFromPushInitiator()
If the destroy channel operation is successful, and you're subscribing with the Push Service SDK, the sample
application calls unsubscribeFromPushInitiator() to unsubscribe from the Push Initiator. The
unsubscribe function passes in the username and password that you typed on the Unregister screen. If you're
not subscribing with the Push Service SDK, the sample application doesn't call
unsubscribeFromPushInitiator().
sample.pushcapture.constructor.prototype.unsubscribeFromPushInitiator
= function() {
document.getElementById("progressinfo").innerHTML = "Unsubscribing
from Push Initiator...";
xmlHttp.open("GET", unsubscribeUrl);
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
var status = xmlHttp.status;
var returnCode = xmlHttp.responseText;
sample.pushcapture.pushInitiatorUnsubscribeHandler(status,
returnCode);
}
};
xmlHttp.send();
};
When a user changes a SIM card in a BlackBerry device, the BlackBerry 10 WebWorks SDK automatically
destroys the channel to the PPG for security purposes. A new user might be using the device, and that user
shouldn't receive push messages that were intended for the previous user. In your application, you should
authenticate all new users, and create a new channel to the PPG.
The sample application passes in the onSimChange() callback function as part of the call to
PushService.create() which creates the PushService object.
blackberry.push.PushService.create(ops,
sample.pushcapture.successCreatePushService,
sample.pushcapture.failCreatePushService,
sample.pushcapture.onSimChange,
sample.pushcapture.onPushTransportReady);
The onSimChange() callback function performs the following actions when a user changes a SIM card in a
device:
• Removes the user and all the push messages associated with the user from the database.
• Removes notifications in the BlackBerry Hub that are associated with the user.
• Unsubscribes the user from the Push Initiator if the user chose to subscribe with the Push Service SDK.
• Displays a message indicating that the SIM card has changed.
There might be occasions when the sample application can't create or destroy a channel because of a push
transport error or a PPG server error. These errors don't occur if you're using the Push Service with the
BlackBerry Enterprise Service.
This error occurs when there's a problem with the mobile network, the user's wireless connection, or the low-
level communications layer that the Push Service uses. When the channel operations fail because of one of
these problems, the Push Service issues a
blackberry.push.PushService.PUSH_TRANSPORT_UNAVAILABLE error code. The sample
application displays an error message to the user when it receives this error code.
This error occurs when the PPG server is unavailable and returns an error. When the channel operations fail
because of this server error, the Push Service issues a
blackberry.push.PushService.PPG_SERVER_ERROR error code. The sample application displays an
error message to the user when it receives this error code.
To handle the push transport error and PPG server error, the sample application specifies an
onPushTransportReady() callback in its call to the static PushService.create function so that the
application can try to create or destroy the channel again.
blackberry.push.PushService.create(ops,
sample.pushcapture.successCreatePushService,
sample.pushcapture.failCreatePushService,
sample.pushcapture.onSimChange,
sample.pushcapture.onPushTransportReady);
sample.pushcapture.constructor.prototype.onPushTransportReady =
function(lastFailedOperation) {
var message = "The push transport/wireless network/PPG is now
available. Please try ";
if (lastFailedOperation == blackberry.push.PushService.
CREATE_CHANNEL_OPERATION) {
message += "registering ";
} else {
message += "unregistering ";
}
message += "again.";
alert(message);
};
The sample application handles these errors by explicitly telling the user about the errors. In your application,
you could handle the errors the same way, or your onPushTransportReady callback could check which
operation failed, and then try the operation again without telling the user about the errors.
The Push Initiator sends the content when it's available so that data traffic is generated only when
necessary. Additionally, with the Push Plus service level, your push solution can store push requests on a
local database on the push server. If the Push Initiator receives a result notification, it can then perform
status queries locally.
End-to-end message visibility
With the Push Plus service level, you can receive up to three status reports for your push request: a
server-level acknowledgment, transport acknowledgment, and application-level acknowledgment. You
can also query the status of a push request for a specific BlackBerry device.
The Push Initiator sends content as bandwidth becomes available so that it doesn't interfere with other
applications, such as phone calls.
The Push Service minimizes the impact on device batteries because the push-enabled application
listens in the background for the Push Initiator to send content to it. The application doesn't need to poll
the push server for content.
Less coding
The Push Service SDK minimizes the amount of code that you need to write to create a Push Service
solution. You can use the APIs in the server-side and client-side libraries to perform these common tasks:
jQuery
If you want to use jQuery or jQuery Mobile in your BlackBerry WebWorks app, you might find the information in
this section helpful.
What is jQuery?
jQuery is a JavaScript library that simplifies many complex actions, such as DOM manipulation and web service
calls, using JSON or AJAX. When you use jQuery, you can minimize the amount of code you write, reduce
development cycles, and simplify the maintenance of your application.
To find out more about jQuery, visit the official jQuery website.
It's important to remember that since jQuery is built on top of JavaScript, the functionality of your code on a
given platform depends on the platform's support of JavaScript. If you already have a desktop web application
that uses jQuery, there is a very good chance that currently existing as well as future desktop and mobile
platforms will simply run your code.
You can use jQuery for commercial application development. To use jQuery in commercial projects, view the
jQuery license.
• You define jQuery Mobile components in your DOM by specifying the appropriate jQuery Mobile markup.
• Once your app loads, the jQuery Mobile framework replaces the components you identified with the
appropriate controls.
For example, let's say you define a layout grid by specifying the ui-grid-a class on a <div> tag. jQuery
Mobile uses the class information only as a reference and attaches any additional CSS, and when applicable,
HTML and JavaScript, that are necessary for the component to function.
Frameworks 233
Things to consider when you're using jQuery
Cross-browser compatibility
jQuery is a JavaScript framework, so its functionality is subject to the features that the underlying browser
specifically supports. If you already have a web application that uses jQuery, you likely tested a variety of
scenarios on the more popular browsers, such as Windows Internet Explorer, Mozilla Firefox, Google Chrome,
Opera, or Safari.
jQuery itself supports the most popular browsers. For information about jQuery support for each browser, visit
the Browser Compatibility page on the jQuery site.
Most desktop computers now have multiple cores, at least 2.0 GHz of processing power, and enough RAM to
accommodate the most inefficiently built applications. Mobile devices like smartphones and tablets have
come a long way, but fall short of many computer benchmarks. The differences in hardware among different
models of BlackBerry devices can significantly affect application performance. Devices with similar hardware
but that run different OS versions also affect application performance.
If you're porting a jQuery-based desktop application to the BlackBerry platform, and even if all jQuery features
are supported on your target BlackBerry platform, you may still need to optimize your app to address the
resource limitations of the platform. jQuery is not designed to be a light framework, such as jqlite, zepto.js,
jq.Mobi, or others, so you might notice a slight overhead in performance in your app, even with the minified
form of jQuery. On the latest BlackBerry devices, limited hardware capability or resouce limitations is much
less of an issue.
UI considerations
BlackBerry WebWorks uses all aspects of HTML5, including JavaScript and CSS, and provides you with
standard UI components that you can use in your application. This gives you the opportunity to be as creative
with your application design as you want.
However, there are times when you simply want to focus on development, and not spend too much time laying
out, skinning, and tweaking various UI components.
You can use the jQuery UI library to simplify the process. This library provides you with many powerful
components. However, this flexbility comes with the same considerations previously noted for using the jQuery
framework in general. Specifically, there will be additional performance overhead. There are options available
that can help you minimize this overhead. For example, jQuery Mobile is better suited for developing on the
mobile platform as it addresses a lot of the performance concerns. Using jQuery Mobile tends to result in
leaner, performance-conscious components. But since jQuery Mobile relies on the core jQuery framework,
there is still some overhead.
You can use any number of UI libraries and extensions to meet the needs for performance and style. A
common concern, however, is that many of these libraries lack the look and feel of native BlackBerry
Frameworks 234
applications. This includes the jQuery Mobile framework. The jQuery Mobile framework does not provide any
BlackBerry specific look and feel either. There are two options to address this.
One option is from an open-source project that is integrated with jQuery Mobile to provide a BlackBerry 10 look
and feel to your BlackBerry WebWorks apps. For more information, visit the GitHub repository for the jQuery
Mobile BlackBerry 10 theme.
The other option is to use the bbUI.js framework. It is a UI framework that is designed specifically for the
BlackBerry platform with a focus on BlackBerry 10. This framework makes a number of optimizations to
increase performance and reduce the memory footprint. Similar to using the jQuery Mobile framework, to use
the bbUI.js framework you set <div> attributes to identify components that the bbUI.js framework then
replaces to turn the components into compelling controls. For more information, visit the GitHub repository for
the bbUI.js framework.
Debugging
Eventually, you're bound to run into issues. With some luck, the problem is simply a missing semicolon. Other
times, you might come across something that's really broken. Here are some ways to more easily solve your
problem.
JavaScript validation
Before you run your code, you should be fairly confident that it will run. JSLint is a great tool for validating code.
Depending on which HTML or text editor you're using, there is likely a JSLint plug-in that you can leverage as
well. Running JSLint will pick out the most common errors for you, including syntax or formatting.
Web Inspector
If you have developed a web application for desktop computers, chances are you've come across some form of
Web Inspector tool to let you examine the source code as it runs. This functionality is also available for
BlackBerry WebWorks applications. See Debugging using Web Inspector for details on using Web Inspector.
Reporting bugs
If you find a bug, you can report it at the appropriate site below:
• jQuery Core
• BlackBerry WebWorks APIs
If you have feedback regarding your experience with BlackBerry WebWorks and jQuery, visit the Web and
WebWorks Development forums to share your insight or see what others are saying.
Resources
Here are some resources that can help you with your jQuery application:
Frameworks 235
BlackBerry WebWorks
Code signing
Debugging
• JSLint
• Debugging using Web Inspector
GitHub repositories
Other resources
• BlackBerry World
Sencha Touch 2
Sencha Touch 2 is a widget library for creating web apps for mobile devices. It contains widgets (also known as
components) that enable you to create web apps for mobile devices with the look and feel of native mobile
apps. It is based entirely on web standards such as HTML5, JavaScript, and CSS3.
• Tab panels
• Nested lists
• Navigation views
• Form controls
• Carousels
• Cards
Sencha Touch 2 also has the following features:
• Data management: Sencha Touch 2 translates JSON objects to Model objects automatically. This enables
you to feed in different types of data sources or destinations. You have the option to use JSON, JSONP,
AMF, and SOAP out-of-the-box.
Frameworks 236
• Offline capabilities: APIs are available to provide offline data storage functionality that is based on HTML5
local storage and session storage mechanisms.
• AJAX support: Full AJAX support, including CORS and JASON-P.
• DOM support: Support for manipulating HTML and XML using the DOM-related methods.
• Feature detection: Automatic detection of features such as geolocation, canvas, and orientation.
• Touch events: Support for a full range of touch events and gestures such as tap, swipe, and pinch.
Further reading
Note: The performance improvements in Sencha Touch 2.1 result from changes to the DOM structure and
additional CSS rules to help the browser render complex layouts better, without making any changes to the
APIs. If you built your app using Sencha Touch 2.0 and used custom CSS, consider reviewing those CSS
selectors if you are updating your app to Sencha Touch 2.1.
Further reading:
Frameworks 237
Dojo Toolkit
Overview
The Dojo Toolkit is a JavaScript toolkit for creating cross-platform JavaScript/AJAX applications. It contains a
rich collection of lightweight and independent modules. The toolkit enables you to use its lightweight solution
for DOM manipulation and AJAX services by allowing you to choose only the modules you need for your
application. It also allows you to create complex JavaScript classes with multiple inheritance.
• Date/time picker
• Accordion views
• Pop up menu with icons
• TabBar views
• Image/content carousel
• Transition effects
Dijit package
You can also add functionality from the Dijit package. The Dijit package includes an extensive library of UI
controls and other useful widgets that are not available in the Dojo Mobile module, such as a color palette or a
calendar. While the widgets in Dojo Mobile are specifically tailored for mobile devices, you might still want to
explore the widgets available in Dijit. As of version 1.8, most widgets in Dijit support mobile device events such
as touch and gesture events.
Frameworks 238
Note: There are plenty of GUI widgets in the DojoX package and there are other packages, such as dgrid
( http://dgrid.io/ ), which offer a high-performance grid that works on mobile and desktop browsers.
To use asynchronous loading of AMD modules, set the "async" property of the Dojo Toolkit to true. It
switches Dojo into baseless Dojo (async mode or AMD mode). With baseless Dojo, your application loads the
module loader first, so that you can pick only the modules that you need in your application. This keeps your
BlackBerry WebWorks application lightweight. Include the following code in your BlackBerry WebWorks
application's index.html file to use the AMD module loader:
<script data-dojo-config="async:true"
src="http://ajax.googleapis.com/ajax/libs/dojo/1.8.0/dojo/dojo.js"></
script>
Note:
While you can include the Dojo loader using a protocol-less URL in desktop applications, in a BlackBerry
WebWorks application, you must include the “http” or “https” protocol identifier to properly locate the external
resource. If you do not specify a protocol, the location that is local to your BlackBerry WebWorks application
becomes the location of the resource by default.
Due to the large number of modules that the Dojo Toolkit provides and the dependencies of some of the
modules, it is suggested that you call the Dojo loader from an online resource. This also means that your
application will require an active Internet connection.
With the AMD module format, module identifiers look like paths (for example: dojox/mobile). Without AMD,
the syntax looks like object references (for example: dojox.mobile).
Frameworks 239
Resources to help you get started
Code sample
The following code shows how to structure the modules and the AMD syntax:
require([
],
function(parser, mobile, compat)
{
parser.parse(); /* Parse the page for widgets
and instantiate them. */
});
Sample application
Visit the WebWorks-Samples repository on GitHub and check out the DojoAppDetails sample. It's a sample
application that displays the application's details by retrieving the details from the application's configuration
file (config.xml).
Further reading
• Getting Started with dojox/mobile: http://dojotoolkit.org/documentation/tutorials/1.8/mobile/tweetview/
getting_started/
• Modern Dojo syntax: http://dojotoolkit.org/documentation/tutorials/1.8/modern_dojo/
• DOM and event handling: http://dojotoolkit.org/documentation/tutorials/1.8/events/
Frameworks 240
• Dynamic content loading: http://dojotoolkit.org/reference-guide/1.8/dojox/mobile/dynamic-content-
loading.html
Enyo 2.0
Overview
Enyo 2.0 is a free and open source JavaScript framework for building cross-platform web apps. You can use
Enyo 2.0 to build apps for the BlackBerry platform. If you already have an Enyo 2.0 based app, you can port it
to the BlackBerry platform.
We are going to demonstrate the porting process using the Onyx Sampler sample app. If you already have an
app built with Enyo 2.0, you can follow the same instructions to port your own app by adapting the instructions
as necessary. Alternatively, you can get the Onyx Sampler sample app and use it to follow the instructions.
Porting apps built using the Enyo 2.0 framework to the BlackBerry platform involves the following activities:
• Incorporate the Enyo core files and the necessary libraries with the app source files.
• Build a BlackBerry WebWorks app from the app source files.
• Install the BlackBerry WebWorks app on the device.
1. Download the OnyxSampler app source files from the BlackBerry WebWorks Community Samples repo on
GitHub.
2. Extract the contents of the compressed file at a location of your choice.
3. From the extracted files, navigate to the following location:
\Enyo-2.0-OnyxSampler\lib\onyx\examples\
4. Copy the OnyxSampler folder to a convenient location (for example, C:\OnyxSampler).
Frameworks 241
Incorporating the Enyo core files and the necessary libraries
The OnyxSampler folder contains the app's source code. To deploy the app, we incorporate the Enyo core files,
and other libraries that the source code refers to, in the OnyxSampler folder. One of the ways you can do this is
to use Enyo Bootplate. Enyo Bootplate contains the latest release of Enyo core files and the most common
libraries. We also use the icon file available in Enyo Bootplate. Here are the steps to accomplish all of this:
1. Download the Enyo Bootplate (bootplate-<x.x.x>.zip) from the Enyo website, where <x.x.x> denotes the
version of Enyo.
2. Extract the contents of the compressed file to a location of your choice.
3. Copy the enyo and lib folders and the icon.png file from the extracted content into the OnyxSampler folder.
4. In the OnyxSampler folder, edit the index.html file as follows:
Further reading
• Enyo Bootplate
• Onyx UI library
• Layout library
Frameworks 242
Building a BlackBerry WebWorks app package
A BlackBerry WebWorks app is packaged into a file with a .bar extension. The BlackBerry WebWorks Packager
(bbwp) is a command-line tool that generates a file from a .zip file, and it is included with the BlackBerry
WebWorks SDK. The .zip file is a BlackBerry WebWorks application archive file. It contains your app source
files and a configuration file named config.xml (BlackBerry WebWorks configuration file).
Building a BlackBerry WebWorks app from your source files involves the following activities:
1. Creating a new BlackBerry WebWorks project. For more information, see Creating a WebWorks project.
2. Placing your app source files in the /www folder of your new project.
3. Generating an unsigned .bar file for testing. For more information, see Building your app for testing.
4. Generating a signed .bar file containing your complete project. For more information, see Building and
signing your complete app.
To complete this task, you must have the BlackBerry 10 WebWorks SDK installed on your computer. You can
download the SDK from the Downloads page.
bbUI toolkit
The bbUI toolkit is an open source JavaScript toolkit that allows you to give your BlackBerry WebWorks
applications the look and feel of a native BlackBerry application.
The bbUI toolkit was created to provide a design language for HTML5 applications using the BlackBerry
WebWorks framework. It provides common UI constructs that are found on the BlackBerry platform so that
you can create an application that follows BlackBerry specific UI guidelines and looks at home on a BlackBerry
device with very little effort.
The bbUI toolkit supports all BlackBerry platforms from BlackBerry Device Software 5.0 through to BlackBerry
7, as well as BlackBerry PlayBook OS and BlackBerry 10. In each case, the toolkit uses CSS that achieves a
similar user experience to the native applications on the platform, and tailors it to suit the capabilities of the
device.
Frameworks 243
Further reading
To learn more about the specific implementation details and functionality of the bbUI toolkit, refer to the bbUI
toolkit project in GitHub. This project site contains overview information, samples, and an extensive wiki that
provides in-depth documentation on how the toolkit is used.
Frameworks 244
Building and Testing
Test your app on a device or a simulator. Debug using Web Inspector. Build and distribute your completed
app.
Configure, package, and test your app. Find out more about using Web Inspector to debug your app.
Targets are created outside of your project. Any targets you create are available for use by any projects you are
working on. You can define as many targets as you have device or simulator PINs. In each case, you specify a
unique target ID and associate that ID with a specific PIN. Then, when you deploy your app to a particular
target device or simulator, you can simply refer to that target by ID.
You only need to set a test target if you want to deploy your app over Wi-Fi or when you have multiple
simulators or devices that you want to test on.
For example, the following command defines the simulator as a target with an ID of mysim:
Parameter Description
<target_id>
A unique name for the target.
-t device | simulator
The target type. If not provided, the default value is device.
-p <password>
The password for the device or simulator. This argument is required
only if the device or simulator is password-protected.
--pin <device-pin>
The PIN of the BlackBerry device, which identifies that device as a
valid host for the debug token. This argument is required only if you
are creating a debug token.
To create a target, you need the IP address of your device or simulator. To get the IP address, follow the steps
below.
On a BlackBerry 10 device:
1. On the home screen, swipe down from the top of the screen or find the Settings app on your home screen.
2. Navigate to Settings > About.
3. In the Category drop-down list, click Network.
4. Under the Wi-Fi heading, note the value under IPv4. This is the IP address you should be supplying when
setting up the device as a test target.
Note: To view the Wi-Fi section on the Network Settings page, you must have Wi-Fi turned on, and the
device must be connected to the Wi-Fi network.
Removing a target
To remove an existing target:
webworks target
webworks serve
3. In your browser, navigate to the following url:
localhost:8000/blackberry10/www
• Debug mode: Debug mode should be used when you are preparing your app for testing. When you build the
app in debug mode, the command packages your resources and plugins together in a .bar file, but does not
sign it. If you intend to test your app on a device, but have not already created and installed a debug token,
you can supply the keystore password, and the build script creates and installs the debug token on the
device for you as well.
Debug mode also enables Web Inspector for the app, which allows you to remotely inspect the source code.
A prompt displays the URL that you can use to connect to and inspect your app. For more information on
using Web Inspector, see Debugging using Web Inspector.
• Release mode: Release mode should be used at the end of the development cycle when you are preparing
your app to be submitted to BlackBerry World. When you build your app in release mode, the command
packages your resources and plugins together in a .bar file, then signs the app. For more information, see
Building and signing your completed app.
1. On the Start menu, click BlackBerry >BlackBerry WebWorks <version>. A new browser window opens,
displaying the BlackBerry 10 WebWorks SDK web tool.
2. Navigate to your project and click Build.
3. Select Debug Mode.
4. Click Build.
The tool packages your app into a .bar file, and places the unsigned copy of the .bar file in the following
location: <your_app_project_directory>\platforms\blackberry10\build\device.
All parameters are optional. Check the table below for parameter details:
Parameters Description
--debug
Indicates that the app will be built in debug mode.
This parameter is optional; --debug is the default
build mode.
-p|--params <JSON-file>
A JSON file containing additional parameters to pass
to downstream tools.
-l|--loglevel <level>
The log level. The level may be one of error, warn,
or verbose.
To build your app in debug mode and deploy it to a simulator for testing:
1. On the Start menu, click BlackBerry >BlackBerry WebWorks <version>. A new browser window opens,
displaying the BlackBerry 10 WebWorks SDK web tool.
2. Navigate to your project and click Build.
3. Select Debug Mode.
4. Select Simulator.
5. Enter the device password used by your simulator.
The tool packages your app into a .bar file, installs it on your simulator, and opens it.
You can build and deploy your app to a BlackBerry 10 simulator using the emulate command.
The emulate command first packages your app resources into a .bar file, deploys the .bar file onto the
simulator, and automatically launches the app. If a .bar file with the same name already exists on the
simulator, the emulate command first uninstalls the existing .bar file before deploying the new .bar file. If you
choose, you can skip the build or launch steps of the process.
If successful, the emulate command launches the app on the simulator. It also places a copy of the
unsigned .bar file in the following location: <your_app_project_directory>\platforms\blackberry10\build
\simulator.
For example, the following sample will deploy the app on the target simulator with the ID of "myZ10sim". If the
app has already been deployed to myZ10sim, it uninstalls the previous version before installing the new
version.
All parameters are optional. Check the table below for parameter details:
Parameters Description
--devicepass <password>
The simulator password. If you omit this parameter,
you will be prompted to supply the simulator
password, if necessary.
--target <target_id>
The target ID of a pre-defined target simulator. In
most cases, this parameter is unnecessary.
--no-build
Causes the command to skip the build step. The
command deploys the most recently built version of
the application.
• Turn on Development Mode on the test target. Note that for security reasons, Development Mode expires
after 10 days and whenever the device is rebooted. For more information, see Enable Development Mode
on a device or simulator.
• Define your device as a test target, if you intend to test on a device over a Wi-Fi network (If you are testing
on a device connected by USB, defining the device as a test target is unnecessary; the tools automatically
detect it). For more information, see Set up your simulator or device as a target.
To build your app in debug mode and deploy it to a device for testing:
1. On the Start menu, click BlackBerry >BlackBerry WebWorks <version>. A new browser window opens,
displaying the BlackBerry 10 WebWorks SDK SDK tool.
2. Navigate to your project and click Build.
3. Select Debug Mode.
4. Select Device.
5. Enter your device password.
6. Enter your keystore password, which you defined when you requested your BlackBerry ID token. If you have
not yet requested your BlackBerry ID token, see set up your computer for testing and signing.
7. Click Build & Install.
The tool packages your app into a .bar file, installs it on your device, and then opens it. If a .bar file with the
same name exists on the device, the SDK first uninstalls the existing .bar file before deploying the new .bar file.
If a valid debug token is not already present on the device, the tool creates and installs the debug token for you
before installing and opening the app. For more information about debug tokens, see A note about using debug
tokens.
If you don't supply a device or keystore password, or supply an incorrect password, the SDK prompts you to
enter the correct password before continuing the deployment process.
You can build and deploy your app to a BlackBerry 10 device using the run command. The target device must
be connected to your computer by USB connection or be connected to the same Wi-Fi network as your
computer.
The run command first builds your app in debug mode and packages the app and its resources into a .bar file.
It then deploys the .bar file onto the device, and automatically launches the app. If a .bar file with the same
name already exists on the device, the run command first uninstalls the existing .bar file before deploying the
new .bar file. If you choose, you can skip the build or launch steps of the process.
If you have not already created and installed a debug token, or your debug token has expired, specify the --
keystorepass <keystore_pw> argument when running the run command. The command creates and
installs the debug token for you as well. For more information about debug tokens, see A note about using
debug tokens.
If successful, the run command launches the app on the device. It also places a copy of the unsigned .bar
file in the following location: <your_app_project_directory>\platforms\blackberry10\build\device.
For example, the following sample will deploy the app on the default target device, as well as create and install
a debug token, if one does not already exist on the device. If the app has already been deployed to the default
target, it uninstalls the previous version before installing the new version.
All parameters are optional. Check the table below for parameter details:
Parameters Description
--devicepass <password>
The device password. If you omit this parameter, you will
be prompted to supply the device password, if necessary.
--target <target_id>
The target ID of a pre-defined target device.
-k | --keystorepass <keystore_pw>
The keystore password, which you defined when you
configured your computer to sign applications. This
argument allows the run command to create and deploy
a debug token to the device on your behalf to allow your
unsigned application to run.
If you omit this parameter and you have not already
created and installed a debug token on the device you are
deploying your app on, you will be prompted to provide
the keystore password.
--no-build
Causes the command to skip the build step. The
command deploys the most recently built version of the
application. This is useful to test an application in release
mode.
--no-launch
Causes the command to skip the launch step. The
command deploys the app to the device, but does not
actually launch the app.
Before you can deploy an unsigned app to the device, the device must have a valid debug token installed on it.
The BlackBerry WebWorks SDK makes it simple to install a debug token on any target device; you only need to
provide the keystore password when you deploy your app to a device. However, there are a few things you
should know about working with debug tokens.
For the SDK to be able to create a debug token for you, you must first request your signing key and set up your
computer for code signing. You can request your free code signing key by completing the form at https://
www.blackberry.com/SignedKeys. For more information about setting up your computer for signing and setting
the keystore password you use for creating your debug token, see Set up your computer for testing and signing.
Debug tokens are not specific to a single app; once you have a valid debug token installed on your BlackBerry
10 device, you can load any unsigned app onto the device for testing until the debug token expires.
Debug tokens are valid for 30 days. When a debug token expires, the BlackBerry 10 OS no longer allows
unsigned apps that rely on that token to run. Note that you are limited to a total of 100 device PINs across all of
active debug tokens associated with the same keystore password. This means that if you create and install
debug tokens on 100 devices, you must wait for some of your debug tokens to expire before you create more.
• To inspect the content of BlackBerry WebWorks applications, you must enable Web Inspector for each
application individually. In a BlackBerry WebWorks application, you enable the Web Inspector by specifying
a command line flag when you package your app.
Once Web Inspector is enabled, the browser or application displays the IP address and port number it will use
to serve the content.
You can use Web Inspector to inspect web content displayed in a BlackBerry WebWorks app. In a BlackBerry
WebWorks app, you enable Web Inspector when you package the app.
To enable Web Inspector, you use the -d option flag when you package your application file.
Note: Web Inspector should only be enabled during the testing phase of development. When the application is
ready for release (that is, when you are signing it for distribution), you should repackage the application
without Web Inspector enabled. (involving code signing). Leaving the debugging port open may allow
unintentional access to your application.
Windows example:
Mac OS example:
When you load a Web Inspector enabled BlackBerry WebWorks application on a BlackBerry device or
simulator and run it, a dialog appears that provides the IP address and the port number required to connect
from your desktop browser.
1. On a BlackBerry 10 device or on the BlackBerry 10 Device Simulator, open the BlackBerry Browser.
2. In the browser, tap
You can now open a connection to the BlackBerry Browser to remotely inspect the page that it is displaying.
Note: Note that Web Inspector only provides a USB IP address (required if you intend to use Web Inspector
over a USB connection) if your device is already connected via a USB connection when Web Inspector is
enabled.
• Verify that your computer has the Google Chrome or Safari desktop browser installed.
• Verify that development mode is enabled on your device.
Once you have enabled Web Inspector in your BlackBerry WebWorks app or in the BlackBerry Browser, you
can remotely connect to your BlackBerry smartphone or BlackBerry tablet to inspect and modify the content.
http://<IP_address>:<port_number>
A list of one or more links is displayed in your browser, representing the webpage currently displayed in
each of the tabs open in the BlackBerry Browser.
3. Click on any of the available links to view the content in Web Inspector.
Elements The Elements panel allows you to inspect the DOM of the current webpage or your
BlackBerry WebWorks app, and adjust settings for attributes and CSS properties.
Changes you make are reflected in the content.
Resources The Resources panel displays information about all the resources that are used by
the current webpage or in your BlackBerry WebWorks app.
Network The Network panel displays information about each HTTP request made as
resources are requested, received, and displayed in the BlackBerry Browser or in
your BlackBerry WebWorks app.
Sources The Sources panel allows you to debug JavaScript code. You can set breakpoints
and step through your code to locate and correct issues.
Timeline The Timeline panel allows you to view how much time it takes for the browser to
load and render the webpage and its resources.
Profiles The Profiles panel allows you to examine how your JavaScript code is utilizing
memory. With the Profiles panel, you can determine where programmatic
inefficiencies exist.
Audits The Audits panel allows you to examine the network utilization and webpage
performance and suggests areas where performance can be improved.
Console The Console panel provides a command-line driven utility that allows you to debug
JavaScript errors or HTML parsing errors.
You can click the Elements icon on the toolbar to display the Elements panel.
The Elements panel is divided into two sections. On the left is the document pane, which displays the DOM
tree of the HTML source document. Each element is displayed as a separate node. You can expand the nodes
of the DOM tree to view the children of a container element. The document pane of the Elements panel is a
good tool to use to view the source of a page; because the panel displays the page as a tree, the document is
easy to view and to navigate, even when the original webpage is minified or poorly formatted and difficult to
read. Within the document pane, you can edit aspects of the DOM, such as attribute values or text.
• Styles: The Styles pane is divided into sections which show each matched CSS rule, and the associated
style declarations. It also displays style values that have been inherited. Inherited values that have been
overwritten by other style declarations are displayed with strikethough text.
• Metrics: The Metrics pane provides a visual representation of the box model, which you can edit to
optimize the layout of a container element on the screen. The box model refers to the amount of space a
container element occupies in a rendered webpage. You can apply styles such as margins, borders, and
padding to an element to adjust the size of the content block and improve the page layout.
• Properties: The Properties pane allows you to view the page as it is viewed by JavaScript code, as a
collection of DOM objects with associated property values. Although some of the property values are
editable, in most cases, it is easier to edit style values in the Styles pane.
1. Click the Elements icon on the toolbar to display the Elements panel.
2. In the document pane, locate and select the element for which you want to alter a style.
3. In the data sidebar, expand the Styles pane to display the style declarations applied to the selected
element.
4. Perform any of the following actions:
• To change the value for a style declaration, double-click the value in the Styles pane to make the value
editable, and type the new value. You can use the Tab key to cycle through the declarations within a
selector to modify more than one value.
• To disable a style declaration, deselect the adjacent check box.
• To add a new style declaration for a selector, double-click the white space below the last style
declaration, and type the new declaration.
• To modify the selector, double-click the selector, and type the new selector value.
5. When you achieve the desired results, propagate the changes to the source document.
1. Click the Elements icon on the toolbar to display the Elements panel.
2. In the document pane, navigate to the node that you want to view or change.
3. Perform any of the following actions:
• To change the value of an attribute, double-click the value in the document pane to make the value
editable and type the new value. You can use the Tab key to cycle through each of the element's
attributes to modify more than one value.
• To change an attribute name, double-click the attribute name and type the new value.
4. When you achieve the desired results, propagate the changes to the source document.
1. Click the Elements icon on the toolbar to display the Elements panel.
2. In the Elements panel, expand the Metrics pane to display the box model associated with the selected
element.
3. Click any of the top, bottom, left, or right values and type the new value. The changed value is propagated
to the associated style declaration in the Styles pane.
4. When you achieve the desired results, propagate the changes to the source document.
You can click the Resources icon on the toolbar to display the Resources panel.
• Frames: Contains the resources for each frame displayed in the content, including images, fonts, scripts,
stylesheets, and other content resources, such as embedded video or Flash files. Subframes within the
main window are displayed as subfolders beneath the main Frames folder.
• Databases: Contains all the database tables that are associated with your content or app.
• Local Storage: Contains all Local Storage objects, that is, storage objects which persist after a browser
session has ended.
• Session Storage: Contains all Session Storage objects, that is, storage objects which are only valid for the
current browser session.
• Cookies: Contains all the cookies associated with the webpage or app.
• Application Cache: Contains the resources included in the manifest of an offline web application.
1. Click the Resources icon on the toolbar to display the Resources panel.
2. In the list in the left pane of the Resources panel, double-click a category to show the resources and
subgroups. Continue to drill down until you locate the resource you are interested in viewing.
3. Double-click the resource in the left pane. The right pane displays the contents of that resource. For
example, selecting an image resource displays the image itself, as well as the file size and URL of the image
file. Selecting a script or style sheet displays the content of that script or style sheet.
You can quickly see additional information about a specific resource by viewing the resource in the Network
panel, which displays information such as file size and transfer rate information.
1. In the list in the left pane of the Resources panel, double-click a category to show the resources and
subgroups. Continue to drill down until you locate the resource you are interested in.
2. Right-click the resource and click Reveal in Network Panel. Web Inspector opens the Network panel and
briefly highlights the selected resource.
You can click the Network icon in the toolbar to display the Network panel. Initially, the panel displays no
information; you must reload the content on the device or simulator to allow Web Inspector to track the HTTP
requests. When loading is complete, the Network panel displays a table similar to the following:
The waterfall timeline plots resources by the total time required to load the resource, from the initial request to
the completion of the download. The pale segment of the resource bar in the chart represents the total latency,
that is, the time the browser engine must wait from the moment it initially makes the request to the moment it
receives the first packet of data for the resource. Two vertical lines on the chart provide mark key page load
milestones:
• The blue line indicates the time at which parsing of the content is complete and the DOMContent event
fires.
• The red line indicates the time at which all the resources have been loaded and the load event fires.
You can customize how the content is displayed in the Network panel; resources can be filtered based on type
or sorted by any of the table headings, and the chart can be reformatted to highlight different time measures.
By default, the Networks panel displays all resource requests in the table. The status bar at the bottom of the
panel contains buttons that allow you to filter which resources are displayed based on the resource type.
By default, when you measure the network activity, Web Inspector charts the network activity in a waterfall
timeline. You can reformat the chart to highlight different time measures.
1. Click the Network icon on the toolbar to display the Network panel.
2. If you have not already done so, on the device or simulator, reload the page to allow Web Inspector to track
and record network activity.
3. In the drop-down list above the chart, select one of the following load time measures:
1. Click the Networks icon on the toolbar to display the Networks panel.
2. If you have not already done so, on the device or simulator, reload the page to allow Web Inspector to track
and record network activity.
3. Click a column heading to reorder the list based on the column data
Debugging scripts
The Sources panel allows you to debug the JavaScript code used by your webpage. By allowing you to set
breakpoints and to step through your code, the Web Inspector can help to locate and correct problems within
your code. When you determine that the script is functioning as intended, you can copy the changes back into
the source file.
To use the Sources panel, you must first enable debugging. Web Inspector prompts you to enable debugging
when you first view the Sources panel; you can choose to enable debugging for just the current session, or to
always enable debugging.
You can click the Sources icon in the toolbar to display the Sources panel. If you have not already enabled
debugging, the Web Inspector prompts you to do so.
A toolbar at the top of the Sources panel allows you to choose the script file you want to inspect and to cycle
between open scripts. It also provides a set of controls that allow you to step through the script displayed in the
document pane.
1. Click the Sources icon on the toolbar to display the Sources panel.
2. In the line gutter of the document pane, click the line at which you want to set a breakpoint. A breakpoint
marker appears in the line gutter, and the new breakpoint is added to the Breakpoints pane, identified by
the script filename and line number. The execution of the script pauses at the specified breakpoint.
3. Perform any of the following actions:
• To continue the execution of the script beyond the current breakpoint, click the Continue button in the
Sources panel toolbar.
• To display the line of code associated with breakpoint in the documents pane, click the breakpoint entry
in the Breakpoints pane. The document pane displays and highlights the associated line.
You can pause the script at any time to get a snapshot of the call stack and variable values.
1. Click the Sources icon on the toolbar to display the Sources panel.
2. In the Sources panel toolbar, click the Pause button.
When the script pauses, the last line of JavaScript to be executed is highlighted. The call stack and the current
in-scope variable values appear in the appropriate panes at the right of the panel.
You can configure Web Inspector to pause the execution of scripts whenever exceptions are thrown. A tri-state
toggle allows you to specify whether to pause for all exceptions, only for uncaught exceptions, or to not pause
for any exceptions.
1. Click the Sources icon on the toolbar to display the Sources panel.
2. Use the Exceptions button in the status bar at the bottom of the Web Inspector window to choose one of
the following behaviors:
• To pause on all exceptions, click the Exceptions button until the icon turns blue.
• To pause only on uncaught exceptions, click the Exceptions button until the icon turns red.
• To not pause on any exceptions, click the Exceptions button until the icon turns gray.
Click the Timeline icon in the toolbar to display the Timeline panel. Initially, the panel displays no information;
you must click Record in the status bar to record the browser engine activity.
Web Inspector adds data to the Timeline panel when it records browser engine activity.
In the top pane, the Timeline panel allows you select which timeline view you want to display. You can choose
three views:
• Events: Displays the time it takes for the browser engine to complete each of the events required to
completely load the content.
• Frames: Displays the browser engine activity for each screen refresh.
• Memory: Displays memory consumption over time.
In the lower pane, the Timeline panel displays a waterfall timeline for the timespan that was selected in the top
pane. The data in the timeline is determined by which mode you select in the top pane of the Timelines panel.
1. Click the Timeline icon on the toolbar to display the Timeline panel.
You can constrain the time span shown in the timeline. In the top pane of the Timeline panel, the portion of
time displayed in timeline in the lower pane is represented with a white background. Two grey slider handles at
the top left and right edges of this white background allow you to increase or decrease the timespan that
appears in the timeline.
1. On the toolbar, click the Timeline icon on the toolbar to display the Timeline panel.
2. If necessary, record the browser engine activity to generate timeline data.
3. In the top pane of the Timeline panel, click and drag a grey slider handle to increase or decrease the time
span.
Web Inspector organizes events by four types: loading (blue), scripting (yellow), rendering (purple), and
painting (green) events. By default, the Timeline panel displays all event types in the table. The status bar at
the bottom of the panel contains check boxes that allow you to show and hide events based on type.
1. Click the Timeline icon on the toolbar to display the Timeline panel.
2. If necessary, record the browser engine activity to generate timeline data.
3. In the status bar at the bottom of the Timeline panel, deselect the event types you want to remove from the
timeline.
Analyze records
The Records pane displays a detailed timeline of events based on the view you have selected. Events are listed
chronologically in the left panel and displayed graphically in the main panel.
Hover over the record you wish to inspect to display a tooltip that lists important information about the event
such as duration or stack traces for rendering and scripting events.
Building and Testing 267
Hover over a paint record to see the affected region of the screen by overlaying the area with a transparent
blue rectangle.
Web Inspector automatically nests synchronous events under their initial event. You can expand and collapse
the events by clicking the arrow beside the initial event. You can also nest asynchronous events using the Glue
asynchronous events to causes button.
1. Click the Timeline icon on the toolbar to display the Timeline panel.
2. If necessary, record the browser engine activity to generate timeline data.
3. In the status bar at the bottom of the Timeline, click Glue asynchronous events to causes
(
) to nest asynchronous events. Click the button again to turn nesting off.
You can revisit past recordings by saving and loading your sessions in the Timeline panel. Timeline data is
stored in .json format.
1. Click the Timeline icon on the toolbar to display the Timeline panel.
2. Right-click anywhere in the panel. Select Save Timeline data to save your recording or select Load
Timeline data to load a past recording.
• For JavaScript files, Web Inspector examines and reports on the CPU usage for each function. You can view
the CPU usage for a particular function, as well as the number of times that function was called.
• For CSS files, Web Inspector examines the processing demands for each selector. Web Inspector records
the amount of time it took to search for matches for a particular selector, as well as the total number of
matches for that selector.
To use the Profiles panel, you must first enable profiling. Web Inspector prompts you to enable profiling when
you first view the Profiles panel; you can choose to enable profiling for just the current session, or to always
enable profiling.
You can click the Profiles icon in the toolbar to display the Profiles panel. If you have not already enabled
profiling, Web Inspector prompts you to do so.
1. Click the Profiles icon on the toolbar to display the Profiles panel.
2. On the Profiles panel, select Collect JavaScript CPU Profile.
3. To start profiling your memory usage, click Start. The button turns red as the Web Inspector is recording
the memory usage.
4. To stop recording, click Stop. When you stop recording, the new profile is added under the CPU Profiles
section in the left pane, and the profile's contents are displayed in the right pane:
• To sort the data by values in any column, double-click the column heading.
• To display calls based on greatest impact on all exceptions or where they occurred in the call stack, in
the status bar at the bottom of the panel, toggle between Heavy (Bottom Up) and Tree (Top down).
• To specify whether values are presented as a time value or as a percentage of the total CPU usage
required to process all the functions, toggle the percent button
(
) on or off.
• To view a single function, select the call in the table and click the focus button
(
).
• To exclude a single function from the data, select the function in the table and click the exclude button
(
).
1. Click the Profiles icon on the toolbar to display the Profiles panel.
2. On the Profiles panel, select Collect CSS Selector Profile.
3. To start profiling your memory usage, click Start. The button turns red as the Web Inspector is recording
the memory usage.
4. To stop recording, click Stop. When you stop recording, the new profile is added under the CSS Selector
Profiles section in the left pane, and the profile's contents are displayed in the right pane:
The profile results indicate the amount of time the browser engine spent matching each selector in the
associated stylesheets, as well as the total number of times the browser engine found a match for the
selector.
) on or off.
The Audits panel can be especially helpful when you design pages for mobile browsers. On mobile browsers,
network latency extends download times, and constrained processing power tends to increase rendering time
and slow webpage performance. As a result, eliminating inefficiencies in your webpage design can have an
significant positive impact.
You can click the Audits icon in the toolbar to display the Audits panel.
Once you have run an audit, Web Inspector adds the report to the list at the left of the panel and displays the
results in the main pane. The audit results suggest improvements you can make to your webpage to increase
efficiencies.
You can access the console through the Console panel or as a split-screen view in the other panels.
• To open the Console panel, click the Console icon in the top toolbar.
• To open the split-screen Console view in another panel, click
The console in Web Inspector lets you inspect DOM elements and objects. Use the inspect() function to
open and select the specified element or object in either the Elements panel or Profiles panel respectively.
To learn more about the Console, and view the Console and Command Line API reference guides, visit Chrome
Developer Tools Guide.
There are a few considerations when you test apps in the work space:
• You must be running BlackBerry 10 OS version 10.2 or later on your BlackBerry 10 device.
Note: Only BlackBerry Enterprise Service 10 version 10.1.3 or later supports the Development Mode
Access to Work Space IT policy.
• If the Development Mode Access to Work Space rule is disabled, apps that you previously tested in the
work space are removed.
• You can overwrite an app that your administrator pushes, but if the Development Mode Access to Work
Space rule is disabled, your app is removed and isn’t reinstalled.
The following information applies to debugging apps in the personal space and the work space:
• When you package your app, set the debug flag (-d). For more information, see Enabling Web Inspector.
• Enable development mode on your device.
• You can deploy your app to your device using a USB cable or over Wi-Fi.
When you debug apps in the work space, you must connect to your device using a Wi-Fi or VPN connection.
• You can use a Wi-Fi profile that was pushed to your device by the BlackBerry Enterprise Server so that the
network is recognized as a work network. You cannot use a Wi-Fi profile that was added manually to debug
an app in the work space. You can find the Wi-Fi IP address under Settings > About > Network.
• Alternatively, you can log in from a wireless network or from a personal or public Wi-Fi network if you use a
VPN that was pushed to your device by the BlackBerry Enterprise Server. You need to use the VPN IP
address. You can find the VPN IP address under Settings > About > Network.
You can install the resulting signed .bar file on the BlackBerry 10 Device Simulator or on a BlackBerry 10
device, without restrictions. You can also submit it to BlackBerry World where it is reviewed, and if approved,
made available to users.
Note: Although you can build your app in release mode at any time, even if you just intend to test it, be aware
that with each release build, you must increase the version number of your app. If you are still in the
development and testing phase and your app is not yet complete, you should build the app in debug mode
instead. For more information about building your app in debug mode, see Building your app for testing.
• Set up your computer for signing. For more information, see Set up your computer for testing and signing.
When the tool has finished building and signing your app, it places the signed copy of the .bar file in the
following location: <your_app_project_directory>\platforms\blackberry10\build\device.
Once the tool has finished running the command, it places a signed copy of the .bar file in the following
location: <your_app_project_directory>\platforms\blackberry10\build\device.
For example, the following command builds version 0.3 of the app, then packages it in a .bar file, and signs it
using the keystore password provided:
Parameters Description
--release
Indicates that the app is built in release mode.
-d, --web-inspector
When included, indicates that Web Inspector is
enabled in the packaged app.
{
"blackberry-signer": {
"-proxyhost": "host",
"-proxyport": "port",
"-proxyusername": "user
name",
"-proxypassword": "password"
}
}
If successful, the run command installs and opens the app on the device. It also places a copy of the
signed .bar file in the following location: <your_app_project_directory>\platforms\blackberry10\build
\device.
For example, the following sample builds version 0.3 of the app, then packages it in a .bar file, signs it using the
keystore password provided, and installs and opens the app on the default target device. If the app exists on
the default target, the command uninstalls the previous version before installing the new version.
Parameters Description
--release
Indicates that the app is built in release mode.
-d, --web-inspector
When included, enables Web Inspector in the
packaged app.
You use the .bar file that is produced by the BlackBerry WebWorks Packager.
For more information about the BlackBerry World storefront, see the following resources:
For more information about signing apps, see Set up your computer for testing and signing.
When you follow best practices, you can improve the performance of your app and make it easier to debug and
maintain.
UI guidelines
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0,
user-scalable=no">
<title>Heading</title>
<link href="favicon.ico" rel="icon" type="image/x-icon">
<link rel="stylesheet" href="css/app.css">
<style type="text/css">
</style>
</head>
<body>
<h1>Heading</h1>
<p>The quick brown fox jumps over the lazy dog.</p>
<script src="js/app.js"></script>
</body>
</html>
• The application is set to full screen by using the following values in the viewport meta tag: initial-
scale=1.0, minimum-scale=1.0, maximum-scale=1.0
• Zooming functionality is turned off by setting user-scalable=no
• For performance improvements, the JavaScript is placed near the bottom of the HTML document. See Put
scripts at the bottom for more details.
If you don't include a document type declaration, your content will not be rendered consistently across
browsers. Each browser might render your content differently. By including a DOCTYPE, browsers are required
to process your content according to the standards for that document type.
HTML5 is the current standard, which you should be using in your BlackBerry applications. HTML5 includes
great new features and functionality that you can leverage in your application.
<!DOCTYPE html>
For BlackBerry devices running BlackBerry 6 and earlier, the browser doesn't support all of the HTML5
features, so you might choose to use the HTML 4.01 Strict or XHTML 1.0 Strict document types instead of the
HTML5 document type.
The application cache (also known as AppCache), allows you to specify the files to cache and make available
even when the user is offline.
To use the AppCache feature, your web application must provide a "manifest" to the browser that lists all the
resources that it needs so that the application can function when offline. After the first time a web page is
loaded, the resources specified in the manifest file are obtained from the application cache, not from the web
server. The manifest is simply a text file that typically has a file extension of .appcache.
CACHE MANIFEST
# 2012-03-08:v1
Your manifest file must be served with the mime-type text/cache-manifest. You may need to add a
custom file type to your web server or configuration. For example, to serve this mime-type in Apache, add this
line to your configuration file (httpd.conf):
To access the manifest file, you must declare it in your HTML document by adding the manifest attribute to
the <html> tag. The manifest attribute points to the manifest file. If your web application has more than
one page, make sure that each page includes the manifest attribute, otherwise those pages won't be part of
AppCache, and they won't work offline.
<html manifest="html5.appcache">
Once your application is cached, it remains cached until one of the following actions occurs:
Keep in mind that the syntax for the viewport meta tag is not the same as the syntax for the @viewport
rule in CSS. This means that you must use commas as delimiters between viewport values, and not
semicolons. If you use semicolon delimiters, the viewport values can be interpreted incorrectly.
Here's an example showing the correct syntax for the viewport meta tag:
When the browser looks for your web page, it will also make a request for your favicon.ico file. If the favicon.ico
file can't be found, you'll see 404 errors in your web server's log. To avoid this, you should always specify a
favicon.ico file in your web pages.
[Mon Aug 20 15:17:49 2012] [error] [client 192.0.2.2] File does not exist:
C:/www/favicon.ico
In the <head> section of your HTML5 documents, add a link tag pointing to your favicon.ico file.
Note:
For BlackBerry WebWorks applications, the resources are typically bundled with the application. The following
information applies mainly to web (browser-based) applications.
The benefits for external files aren't experienced in every situation. Before you start externalizing your
application's resources, consider only making the resource external if:
Here are some tips when using external files in your web application:
• Source your files off a well-known host, which can reduce the number of DNS lookups.
• Spread the resources out to another domain. The browser has a limited number of connections that it will
open to a particular domain; if you spread the files out to another domain, it increases the browser’s
freedom to parallelize requests.
• Use CDN (Content Delivery Network) hosted files for common JavaScript libraries (for example, jQuery).
This can improve your web application's performance by decreasing latency and improving what's cached.
For example, if a user has visited another site that uses CDN hosted files, those files will already be cached
on the device. When the user visits your site for the first time, the library will already be available. Here's a
code example that uses the Google's CDN-hosted jQuery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/
jquery.min.js">
</script>
• Analyze the performance of your web application by using the Web Inspector. For more information about
the Web Inspector, see Debugging using Web Inspector.
You can add your stylesheets to your HTML document by using the <link> tag.
<!DOCTYPE html>
<html>
<head>
If you use the @import rule to import style sheets, in some browsers, it behaves as though your stylesheet is at
the bottom of the HTML document. This is not the behavior you want because because it prevents the web
page from loading progressively.
<style>
@import url("styles2.css");
</style>
In addition, the @import rule can be nested inside CSS files, preventing the browser from loading your
stylesheets in parallel. For example, if styles1.css contained the following:
@import url(styles2.css)
The browser must first retrieve styles1.css and then retrieve styles2.css.
Putting your script at the bottom also improves parallel downloading components in parallel. While a script is
downloading, parallel downloading is disabled. If the script is at the top, the browser must wait for the script to
download before downloading any other components.
Another advantage to putting the script in the BODY (before the closing body tag) is that you don't need to
check to see if the DOM is loaded, because everything in the DOM has already loaded.
<html lang="en">
<body>
...
<script src="js/app.js"></script>
</body>
</html>
<html lang="en">
<head>
<script src="js/app.js"></script>
</head>
<body onload="init();">
...
</body>
</html>
Note:
Some third-party frameworks require that you include the scripts at the very top of the HTML document. Refer
to the third-party's documentation for more information.
Unfortunately, the DEFER attribute behaves differently between browsers. To avoid cross-browser issues, you
can use the "lazy loading" approach. That is, avoid loading scripts until they are needed.
function lazyload() {
var elem = document.createElement("script");
elem.type = "text/javascript";
elem.async = true;
elem.src = "app.js"; // contains more than 25 uncalled functions
if (window.addEventListener) {
window.addEventListener("load", lazyload, false);
} else if (window.attachEvent) {
window.attachEvent("onload", lazyload);
} else {
window.onload = lazyload;
We'd expect to read this selector as: find the element with the id="home", then apply the color style to every
anchor (<a> tag) it contains. You might think this would be quick because we are using an ID tag and ID
selectors are typically fast. However, because the browser reads the selectors from right to left, here's how the
browser actually reads the rule: find every anchor tag, then check that its parent element has an id="home",
keep checking until a match is found or until the end of the HTML document is reached.
A more efficient way to write this style is to avoid the descendant selector and use a class that's associated
with the anchor tag, such as:
#main-navigation { } /* ID (Fastest) */
body.home #page-wrap { } /* ID */
.main-navigation { } /* Class */
ul li a.current { } /* Class *
ul { } /* Tag */
ul li a { } /* Tag */
* { } /* Universal (Slowest) */
#content [title='home'] /* Universal */
Note:
Although there might be a performance benefit in using appropriate CSS selectors, you shouldn't take the
selector rules too far because you might see a disproportionate increase in maintenance costs vs. the
performance benefits you gain. As always, you should analyze the performance of your application by using the
Web Inspector. For more information about the Web Inspector, see Debugging using Web Inspector.
There are four types of selectors. ID and class selectors are more efficient than tag or universal selectors.
Selector Description
ID This selector matches the unique element in the page with the specified ID.
Class This selector matches all elements with a class attribute contain the class name.
Tag or type This selector matches every instance of the element type in the document tree.
Universal This selector, written using *, matches every element in the document.
The following example shows where a class selector would be more efficient that a descendant selector:
Slower
ul li {color: blue;}
ol li {color: red;}
Because a browser downloads each image separately, it helps the browser to know the image's height and
width. This allows the browser to create an appropriately sized placeholder so it can determine the page layout
while the image downloads. Otherwise, the browser has to reflow the page after each image downloads and the
image's real size becomes known. This slows the rendering of the page and negatively affects the user
experience.
When you specify the dimensions of the image, it should be the actual image size. Do not scale images on the
fly by specifying a different width/height than the actual image. For example, say an image file is actually 50 x
50 pixels, but you want the image to display smaller, so you set the dimensions to 20 x 20 pixels in the HTML.
Rescaling images consumes CPU cycles, causes repainting which uses more memory, and slows page
rendering.
Instead, create your images at the appropriate size. This will not only improve rendering speed, but also avoid
downloading an unnecessarily large file. Remember that most mobile data plans are not unlimited, so you want
to reduce the data usage for the user.
To set an image's size, you can use the width and height attributes of the <img> tag or the width and height
CSS properties. There is no need to use both because CSS properties override HTML attributes.
Examples
HTML
<img id="logo" src="logo.jpg"
alt="Company logo" height="100"
width="100" />
Inline CSS
<img id="logo" src="logo.jpg"
style="width: 100px; height:
100px;">
Here's an example that uses the nth-child notation along with CSS sprites to create a navigation menu:
#navcontainer li {
background-image: url('spritebg.jpg'); /* single image */
}
#navcontainer ul li:nth-child(1) {
background-position: -130px -700px; /* position = xpos ypos */
}
#navcontainer ul li:nth-child(2) {
background-position: -130px -718px;
}
#navcontainer a {
width: 250px; /* size */
height: 18px;
}
... {
-webkit-transform: <transform function>;
}
img.rotate3d {
-webkit-transition: -webkit-transform 1s ease-in-out;
-webkit-transform: rotate3d(0, 0, 1, 0deg);
}
img.rotate3d:hover {
-webkit-transform: rotate3d(0, 0, 1, 15deg);
}
Keep in mind that triggering hardware acceleration doesn't mean you'll have a faster app. An element with a
3D transform applied to it (or other hardware-accelerated elements) is painted into GPU memory so that it can
take advantage of accelerated transforms. This technique does not speed up the cascade, layout, JavaScript,
or the painting of anything, it simply speeds up the transform.
Note:
Important: You should use this technique sparingly! The GPU is not shy about using resources, including
battery power and memory.
... {
overflow-x: scroll;
-webkit-overflow-scrolling: touch;
}
When you make this addition, it allows for momentum and smoother scrolling, a visual bounce effect when the
user reaches the top or bottom of the list, and a more responsive touch interaction.
//create an object
var obj = new Object();
obj.debug = false;
obj.lang = "en";
//create an array
var arr = new Array("one", "two", "three");
Although the traditional method of creating objects and arrays is technically accurate, the literal notation
evaluates more quickly and requires less code. Here's the previous code written using literal notations:
//create an object
var obj = {debug: false, lang: "en"};
//create an array
var arr = ["one", "two", "three"];
Using global variables can also affect the performance of your script. If code inside a function or another scope
references a particular global variable, the script engine must go through each scope until it reaches the global
scope. A variable in the local scope is found more quickly. Variables in the global scope also persist through
the life of the script, whereas local scope variables are destroyed when the local scope is lost. The memory that
local variables use can then be freed by the garbage collector.
The following code snippet defines a function and variables that are global in scope. As a result, it is both
inefficient—since it persists in memory much longer than necessary—and at risk for future namespace
collisions.
In the following example, we've rewritten the previous snippet to define and use a namespace. The namespace
object, myApp, is created and assigned values and functions to it. By using this technique, we limit the scope
of the variables and functions.
var myApp = {
lang: "en",
debug: true,
};
Structuring your code this way helps avoid name collisions and as your code base grows, you can neatly
separate the objects into logical files.
When an error occurs in the try block, execution immediately stops and jumps to the catch block, where the
error object is provided. When the catch block is executed, the error object is assigned to a new variable and
that new variable lasts for the duration of the catch block; it's destroyed when the catch block ends. The
creation and handling of this new runtime variable might affect the performance of your application. You
should avoid using try-catch blocks within a critical function or loop.
We've re-written the previous code to improve the effectiveness of the try-catch block. Instead of including
the try-catch block within the loop, we restructure the code so that the try-catch block surrounds the
loop.
Method Example
Using the concatenation (+) operator str = "h" + "e";
Using the shorthand assigment (+=) operator str += "l";
Using string.concat() str = str.concat("l", "o");
Using array.join() str = ["h", "e", "l", "l",
"o"].join("");
If you're concatenating just a few strings, then any of the above methods are acceptable and perform equally.
However, if the length and number of strings increase then you should optimize how you concatenate strings.
When you concatenate strings by using the concatenation (+) operator, the following occurs:
You can speed up concatenation and use less memory by avoiding the temporary string. In the following
example, we create two distinct statements and directly assign the result with the assignment operator.
str += "x";
str += "y";
In the following example, we create a typical but inefficient loop. For each iteration of the loop, the
arr.length object is re-calculated, causing an unncessary hit on performance.
You can improve the previous loop by caching the arr.length object so it's calculated only once. Now, the
control condition uses only local variables, thereby improving the speed of the loop.
To further improve your loop, consider executing the loop in reverse. If you're not concerned about the order in
which the array is processed, you can improve the loop execution by reversing the order with the decrement
• Poor performance: The eval() method must invoke the compiler to pass the string and execute the
results. In addition, the evaluated code is not cached.
• Security issues: The eval() method can make your code vulnerable to various injection attacks as it
executes any code given to it. You should never use eval() with strings of unknown or untrusted origins.
• Impairs debugging: Code that includes eval() can be more difficult to debug because the code from
eval() is dynamically generated. Also, the eval form is harder to read and can often be written in a
cleaner and clear way without the use of eval().
myValue = myObject[myKey];
The timeout methods setTimeout() and setInterval() can also take a string and execute code thereby
acting like the eval() method. You should avoid passing a string to setInterval() and setTimeout()
and instead pass a function.
The HTML in the following example contains two buttons that should perform an action when clicked.
Traditionally, we would simply attach an event handler to each item like this:
<a href="javascript:handleClick();">Click</a>
<button id="btn1" onclick="handleClick();">One</button>
<button id="btn2" onclick="handleClick();">Two</button>
To improve the performance of this code, we use event delegation by adding a single onclick event handler
to the div that contains the buttons. Since all the buttons are children of the div, their events bubble up and
are handled by the function. The event target is the button that was clicked, so we can check the id property
to determine the appropriate action. With this approach, we retrieved one DOM element and attached a single
event handler, thereby reducing the amount of memory used.
<div id="btngroup">
<button id="btn1">One</button>
<button id="btn2">Two</button>
</div>
document.getElementById("btngroup").addEventListener("click", function
(event) {
switch (event.srcElement.id) {
case "btn1":
handleClick();
break;
default:
handleClick;
}
}, false); // type, listener, useCapture (true=beginning, false=end)
Using event delegation also makes it easier to add and remove buttons in the future.
The size of the DOM slows down all operations related to it, including manipulations, reflows, and traversing
the DOM. One way to improve these operations is to make your DOM smaller.
Whenever you are accessing DOM elements, you should be caching the objects that you access. More often
than not, your script will repeatedly access a certain object, as in the following example:
Slow:
In the above example, the document.images object is accessed multiple times. This is inefficient because
for every iteration of the loop, the browser must look up the document.images object twice: once to read
the .length property and ascertain if i < document.images.length and once to read and change the
value of the .src property.
A more efficient version uses a variable to store document.images, which can then be accessed by your
script.
Better:
A reflow involves changes that affect the layout of a portion of the page (or the whole page) and causes the
reflow of all child and ancestor elements (for example, a table). With a reflow, the browser looks to see how
your changes affect the overall layout of the document. The browser recalculates the geometrics of the
changed element as well as the geometrics and positions of other elements that could be affected by the
change.
A reflow is needed whenever you change the layout of the page. A reflow can occur if you:
Here are some CSS and JavaScript tips for minimizing reflows and repaints:
CSS tips
• Change classes on the element you wish to style as low in the DOM tree as possible to limit the scope of the
reflow to as few nodes as possible.
• Avoid setting multiple inline styles and try instead to combine the styles into a external class, which causes
only one reflow when the attribute is changed.
• Apply animations to elements whose position are fixed or absolute as they don't affect the layout of other
elements, so only a repaint will occur rather than a reflow.
• Avoid using tables for layout. If you need to use a table for data, use a fixed layout (table-
layout:fixed).
JavaScript tips
• Create a copy of the node you want to update by using cloneNode(), work on that copy, and then
replace the old node with your updated copy.
// slower
var subElem = document.createElement('div'),
elem = document.getElementById('animated');
elem.appendChild(subElem);
elem.style.width = '320px';
// faster
var subElem = document.createElement('div'),
elem = document.getElementById('animated');
elem.style.display = 'none'; // will not be repainted
elem.appendChild(subElem);
elem.style.width = '320px';
elem.style.display = 'block';
// slower
var list = ['foo', 'bar', 'baz'], elem, contents;
for (var i = 0; i < list.length; i++) {
elem = document.createElement('div');
content = document.createTextNode(list[i]);
elem.appendChild(content);
document.body.appendChild(elem); // multiple reflows
}
// faster
var fragment = document.createDocumentFragment(),
list = ['foo', 'bar', 'baz'], elem, contents;
for (var i = 0; i < list.length; i++) {
elem = document.createElement('div');
content = document.createTextNode(list[i]);
fragment.appendChild(content);
}
document.body.appendChild(fragment); // one reflow
BlackBerry WebWorks 2.0 is built on Apache Cordova, an open source development framework that lets you
create applications using web technologies. By aligning with Apache Cordova, BlackBerry WebWorks apps are
now easier to output to multiple platforms.
This release of the BlackBerry 10 WebWorks SDK builds upon the features provided in the previous Beta
release.
S
u
p
p
o
r
t
f
o
Alignment with Apache Cordova 3.4 r
This release of the BlackBerry 10 WebWorks SDK is built upon Apache Cordova 3.4. Cordova 3.4 brings with U
it a couple of changes that impact the WebWorks SDK: b
u
• config.xml is now stored in the root folder of the project, instead of in the www/ subfolder. If you need to
make any manual changes to the file, make sure you change only the version in the root folder.
n
• You can now specify the --release switch when using the run command to deploy a signed version of
t
your .bar file to a device. u
1
2
.
0
4
T
h
e
B
l
a
c
k
B
e
n
o
w
p
r
o
v
i
d
e
s
a
n
i
n
s
t
a
l
l
e
r
f
o
1
2
.
0
4
,
a
v
a
i
l
a
b
l
e
f
r
o
m
t
h
e
W
e
b
W
o
r
k
s
D
o
w
p
a
g
e
.
D
o
n
'
t
f
o
r
g
e
t
t
o
m
a
k
e
t
h
e
i
n
s
t
a
l
l
e
r
Note:
If you are installing to Mac OS X Mountain Lion (10.8) or later, you will need to change you system
preferences to successfully install the SDK. To change your system settings:
Note:
Known Issues
JI: 15531 The blackberry.system.hasCapability()
method does not accurately return the capabilities of
the device.
JI: 16022 The Cordova Geolocation plugin does not return the
expected value for Heading. When testing the
Location test page of the mobile spec, the app returns
an NaN.
JI: 16254
The
blackberry.sensors.supportedSensors
property does not return an array of strings as
documented. As a workaround, use