Class WL.Client

WL.Client

Description:
This collection of topics lists the public methods of the IBM® MobileFirst® runtime client API for mobile apps, desktop, and web. WL.Client is a JavaScript client library that provides access to IBM MobileFirst capabilities. You can use WL.Client to perform the following types of functions:
  • Initialize and reload the application
  • Manage authenticated sessions
  • Obtain general application information
  • Retrieve and update data from corporate information systems
  • Store and retrieve user preferences across sessions
  • Internationalize application texts
  • Specify environment-specific user interface behavior
  • Store custom log lines for auditing and reporting purposes in special database tables
  • Use functions specific to iPhone, iPad, Android, and Windows Phone 8 devices
Calls to the MobileFirst Server
WLClient uses asynchronous JavaScript calls, which accept an options parameter. (See the "The options Object" topic elsewhere in this documentation.) Success and failure handlers receive a response parameter. The API consists of many calls, listed here.
WLClient uses asynchronous JavaScript calls to access the IBM MobileFirst Server. Each asynchronous method accepts an options parameter, which includes success and failure handlers to communicate the results of the call. If you want to be notified when an asynchronous function returns, you must supply these callback functions within the options parameter when you call the function.
Augmented Options
The options parameter often contains additional properties applicable to the specific method that is being called. These additional properties are detailed in the description of the specific method.
Augmented Response
The success and failure handlers of all asynchronous calls always receive a response parameter that contains a common set of properties. Some calls pass additional properties in the response object of the success and failure handlers. In such cases, these additional properties are detailed in the description of the specific method.
Quick Reference
The MobileFirst Client API consists of the following API methods:
  • General application methods
    • Lifecycle: WL.Client.init, WL.Client.reloadApp
    • Connectivity: WL.Client.setHeartBeatInterval, WL.Client.connect, Connectivity-related JavaScript Events
    • Data access methods: WL.Client.invokeProcedure
    • Application properties methods: WL.Client.getEnvironment
    • Error handling: WL.App.getErrorMessage
    • Debugging: The WL.Logger object

  • Mobile functionality and UI
    • Network details: WL.Device.getNetworkInfo
    • Badge: WL.Badge.setNumber
    • Dialog box: WL.SimpleDialog
    • Accessing native pages on mobile apps: WL.NativePage.show
    • Switching between HTML Pages: WL.Fragment.load,Class WL.Page: Both deprecated

  • Web and desktop widget methods
    • Globalization: WL.Client.getLanguage

  • Mechanisms used by the WLClient methods
    • The Options Object, Timeout
Requires:
prototype.js
gadgetCommunicationAPI.js
wlcommon.js
messages.js
worklight.js
Note:
Although JavaScript does not support encapsulation, do not use any method or member not listed in this document. Their semantics or existence is not guaranteed in future versions of the IBM MobileFirst Client API.

Method Summary
Method Attributes Method Name and Description
 
addGlobalHeader(headerName, headerValue)
The HTTP header is used in all requests until removed by the WL.Client.removeGlobalHeader API call.
 
Clears a previously saved value associated with key.
 
Creates a challenge handler responsible for handling responses from a third party gateway.
 
Creates a challenge handler object to handle challenges that are sent by the MobileFirst Server.
 
deleteCookie(name)
Deletes a cookie from the native HTTP client cookie storage.
 
Retrieves cookies from the native HTTP client.
 
Gets the display name of the device.
 
 
This method returns the language or dialect code of the language currently being used for the application.
 
getSharedToken(Object)
Returns the previously saved value associated with key.
 
init(options)
Initializes the WL.Client object.
 
invokeProcedure(invocationData, options)
 
pinTrustedCertificatePublicKey(certificateFilename)
Pins the host X509 certificate public key to the client application.
 
Reloads the application It can be used to recover an application from errors.
 
removeGlobalHeader(headerName)
 
setCookie(cookie)
Adds a cookie to the native HTTP client.
 
setDeviceDisplayName(deviceDisplayName, options)
Sets the display name of the device.
 
Sets the interval of the heartbeat signal.
 
setSharedToken(Object)
Saves a key/value pair such that it is available to other applications.
Method Detail
addGlobalHeader
addGlobalHeader(headerName, headerValue)
The HTTP header is used in all requests until removed by the WL.Client.removeGlobalHeader API call.
Parameters:
headerName - Mandatory. The name of the header to be added.
headerValue - Mandatory. The value of the header to be added.
Deprecated:
Since version 8.0 Adds an HTTP header to be used in server requests issued by an IBM MobileFirst framework.
Example:
WL.Client.addGlobalHeader("MyCustomHeader","abcdefgh");

clearSharedToken
clearSharedToken(Object)
Clears a previously saved value associated with key. This function clears a previously saved value associated with key from applications participating in simple shared data who are in the same application family, defined by the same family name and same application signing key. This API call is only applicable in Android and IOS environments. It is a safe, but no-op, call in other environments.
Parameters:
Object - Mandatory. Object containing the key to clear, like {key: 'myKey'}
Returns:
Promise

createGatewayChallengeHandler
createGatewayChallengeHandler(gatewayName)
Creates a challenge handler responsible for handling responses from a third party gateway. An arbitrary name must be supplied as a parameter. When you create a GatewayCheckChallengeHandler, you must implement the following methods:
  • canHandleResponse() - Called each time that a response is received from the server. It is used to detect whether the response contains data that is related to this challenge handler, and returns TRUE if so, and FALSE if not. If this method returns TRUE, the framework will call handleChallenge
  • handleChallenge() - The MobileFirst framework calls this method only when canHandleResponse(). This function is used to perform required actions, such as hiding the application screen, displaying the login screen, or other actions required to pass the challenge successfully.
The following APIs are available on the generated GatewayCheckChallengeHandler:
  • cancel() - Notifies the MobileFirst framework that the authentication process needs to be canceled. The MobileFirst framework then disposes of the original request that triggered the authentication.
  • submitLoginForm(reqURL, options, submitLoginFormCallback)
  • - Call this method to send collected credentials to a specific URL. The developer can also specify request parameters, headers, and callback.
  • submitSuccess - Call this method to notify the MobileFirst framework that the authentication successfully finished. The MobileFirst framework then automatically issues the original request that triggered the authentication.
Parameters:
gatewayName - An arbitrary name representing the challenge.

createSecurityCheckChallengeHandler
createSecurityCheckChallengeHandler(securityCheckName)
Creates a challenge handler object to handle challenges that are sent by the MobileFirst Server. A SecurityCheckChallengeHandler works only with a security check that is based on the MobileFirst authentication protocol, that is, server side security check instance extends one of the MobileFirst provided security checks, There must be only one challenge handler per security check. To comply with the MobileFirst authentication protocol, the challenge that the challenge handler receives must be a JSON object.

When you create a SecurityCheckChallengeHandler, you must implement the following methods:

  • handleChallenge() - The MobileFirst framework calls this method only for the relevant challenge. This function is used to perform required actions, such as hiding the application screen, displaying the login screen, or other actions required to pass the challenge successfully.
  • handleSuccess() - This method is called when the MobileFirst Server reports an authentication success.
  • handleFailure() - This method is called when the MobileFirst Server reports an authentication failure.
The following APIs are available on the generated GatewayCheckChallengeHandler:
  • cancel() - Notifies the MobileFirst framework that the authentication process needs to be canceled. The MobileFirst framework then disposes of the original request that triggered the authentication.
  • submitChallengeAnswer(answer) - Call this method to send an answer back to the security check that triggered this challenge. The answer should be in a JSON format.
Parameters:
securityCheckName - security check name that represents the challenge, Used to identify which security check requires authentication.

deleteCookie
deleteCookie(name)
Deletes a cookie from the native HTTP client cookie storage. This function is asynchronous and returns a promise.
Parameters:
name - Mandatory. Cookie name.
Returns:
Promise
Example:
WL.Client.deleteCookie(myCookie).then(successFlow);

getCookies
getCookies()
Retrieves cookies from the native HTTP client. This function is asynchronous and returns a promise. The array of cookies will be passed as a parameter to resolve callback.
Returns:
Promise
Example:
WL.Client.getCookies().then(function(cookies){...})
Note:
HttpOnly and Secure cookies are not returned.

getDeviceDisplayName
getDeviceDisplayName(options)
Gets the display name of the device. The display name is retrieved from the MobileFirst Server registration data.
Parameters:
{Object} options - An object that contains onSucess and onFailure completion callback functions.
The onSuccess function receives a JSON object parameter that contains the server's response, which includes the display name of the the device or null if no display name was set. For example:
  • { responseJSON: { deviceDisplayName: "John's Device" } }
  • { responseJSON: { deviceDisplayName: null } }

getEnvironment
getEnvironment()
Returns:
A constant that identifies the type of environment. The valid values are defined in the WL.Environment variable in the worklight.js file, and are as follows:
  • WL.Environment.ANDROID
  • WL.Environment.IPAD
  • WL.Environment.IPHONE
  • WL.Environment.PREVIEW (when the application runs in Preview mode)
  • WL.Environment.WINDOWSPHONE8
  • WL.Environment.WINDOWS8
  • WL.Environment.WINDOWS

When an app is running in Preview mode, this method returns WL.Environment.PREVIEW, regardless of the previewed environment. There are two reasons for this behavior:
  • Environment - specific code can fail when invoked from the browser (because the environment might support features that are not available in the browser).
  • WL.Client behaves differently in different environments (for example, cookie management).

A good practice is to rely on the IBM MobileFirst UI optimization framework and separate environment-dependent JS to separate files rather than using the WL.Client.getEnvironment() function.
Deprecated:
Since version 8.0 Identifies the type of environment in which the application is running. Such as iPhone, Android, or Windows.

getLanguage
getLanguage()
This method returns the language or dialect code of the language currently being used for the application.
Returns:
The language or dialect code of the currently set language, or NULL if no language is set. The language or dialect code has the format ll or ll-cc, where ll is a two-letter ISO 639-1 language code and cc is a two-letter ISO 3166-1-alpha-2 country or region code.
Deprecated:
Since version 8.0 Return the language code of the language being used.
Note:
This method is not relevant for mobile operating systems. Use mobile locale methods instead.

getSharedToken
getSharedToken(Object)
Returns the previously saved value associated with key. This function retrieves a previously saved value associated with key from application participating in simple shared data who are in the same application family, defined by the same family name and same application signing key. This API call is only applicable in Android and IOS environments. It is a safe, but no-op, call in other environments.
Parameters:
Object - Mandatory. Object containing the key to retrieve, like {key: 'myKey'}
Returns:
Promise containing the retrieved value, or null if no value is found

init
init(options)
Initializes the WL.Client object. The options of this method reside in the initOptions.js file.
Parameters:
options - An optional options object augmented with the following additional optional properties:
Property Description
Timeout

An integer value, denoting the timeout in milliseconds. The timeout affects all calls from the app to the MobileFirst Server. If not specified, a timeout of 30,000 milliseconds (30 seconds) is used.

messages

A dictionary object for localizing texts, located in the messages.js file. If not specified, the default object Messages (in the same file) is used.

onUnsupportedVersion

A failure-handling function invoked when the current version of the application is no longer supported (a newer application has been deployed to the server). For more information about the signature of failure-handling functions, see The Options Object.

onRequestTimeout

A failure-handling function invoked when the init() request times out. For more information about the signature of failure-handling functions, see The Options Object.

onUserInstanceAccessViolation

A failure-handling function invoked when the user is trying to access an application that was provisioned to a different user. For more information about the signature of failure-handling functions, see The Options Object.

onErrorRemoteDisableDenial

A failure-handling function invoked when the server denies access to the application, according to rules defined in the IBM MobileFirst Console. If this function is not provided, the application opens a dialog box, which displays an error message defined in the IBM MobileFirst Console. When used, the function can provide an application-specific dialog box, or can be used to implement additional behavior in situations where the server denies access to the application. It is important to ensure that the application remains offline (not connected).

Parameters:
message: This parameter contains the notification text that you defined in the MobileFirst Console, which indicates that an application is denied access to the MobileFirst Server.
downloadLink: This parameter contains the URL that you defined in the MobileFirst Console to download the new version of the application, that users can find in the appropriate application store.

Example


var wlInitOptions = {
	onErrorRemoteDisableDenial : function (message, downloadLink) {
	WL.SimpleDialog.show(
		"Application Disabled",
		message,
		[{text: "Close application", handler: function() {WL.App.close();}},
		{text: "Download new version", handler: function() {WL.App.openURL(downloadLink, "_blank");}}]
		);
	}
};

onErrorAppVersionAccessDenial

A failure-handling function invoked when the server denies access to the application, according to rules defined in the IBM MobileFirst Console. If this function is used, the developer takes full ownership of the implementation and handling if Remote Disable took place. If the failure-handling function is not provided, the application opens a dialog box, which displays an error message defined in the IBM MobileFirst Console.
Note: onErrorAppVersionAccessDenial is deprecated since V5.0.6. Instead, use onErrorRemoteDisableDenial.

validateArguments

A Boolean value, indicating whether the IBM MobileFirst Client runtime library validates the number and type of method parameters. The default is true.

autoHideSplash

A Boolean value, indicating whether the IBM MobileFirst splash-screen will be auto-hidden. To disable automatic hiding of the splash screen set this property to false. Default is true.

Note:
The onSuccess function is used to initialize the application.
If an onFailure function is not passed, a default onFailure function is called. If onFailure is passed, it overrides any specific failure-handling function.

invokeProcedure
{Promise} invokeProcedure(invocationData, options)
Parameters:
invocationData - Mandatory. A JSON block of parameters. For a description of the structure of the parameter block.
The WL.Client invokeProcedure function accepts the following JSON block of parameters:

{
	adapter : 'adapter-name',
	procedure : 'procedure-name',
	parameters : []
}
Property Description
adapter

Mandatory. A string that contains the name of the adapter as specified when the adapter was defined.

procedure

Mandatory. A string that contains the name of the procedure as specified when the adapter was defined.

parameters

Optional. An array of parameters that is passed to the back-end procedure.

options - Optional. A standard options object, augmented with the following property:
  • The success handler response object can contain the following properties:
    Property Description
    invocationContext

    The invocationContext object that was originally passed to the MobileFirst Server in the callback object.

    invocationResult

    An object that contains the data that is returned by the invoked procedure, and the invocation status. Its format is as follows:

    
    invocationResult = {
    	isSuccessful: Boolean,
    	errors : "Error Message"
    	// Procedure results go here
    }
    
    Where:
    • isSuccessful – Contains true if the procedure invocation succeeded, false otherwise. If the invocation failed, the failure handler for the request is called.
    • errors – An optional array of strings containing error messages.

    parameters

    Optional. An array of parameters that is passed to the back-end procedure.

  • timeout: Integer. Number of milliseconds to wait for the server response before failing with a request timeout. The default timeout value is 30000 milliseconds (30 seconds).
    • The maximum timeout value in any Windows Phone environment is 60000 milliseconds (60 seconds).
  • The failure handler of this call is called in two cases:
    • The procedure was called but failed. In this case, the invocationResult property is added to the response received by the failure handler. This property has the same structure as the invocationResult property returned to the success handler, but the value of the isSuccessful attribute is false. For the structure of the invocationResult property, see invocationResult.
    • A technical failure resulted in the procedure not being called. In this case, the failure handler receives a standard response object.
Returns:
{Promise} Resolved when the operation is successful. Rejected when there is a failure.
Deprecated:
Since version 8.0. Use WLResourceRequest instead Invokes a procedure that is exposed by an IBM MobileFirst adapter. Prior to invoking a procedure, a connect request to the MobileFirst Server is first initiated.

pinTrustedCertificatePublicKey
{Promise} pinTrustedCertificatePublicKey(certificateFilename)
Pins the host X509 certificate public key to the client application. Secured calls to the pinned remote host will be checked for a public key match. Secured calls to other hosts containing other certificates will be rejected. Some mobile operating systems might cache the certificate validation check results. Your app must call the certificate pinning method before making a secured request. Calling this method a second time overrides any previous pinning operation.
Parameters:
certificateFilename - - the name of the certificate file that is located under the certificate folder located in the application root
Returns:
{Promise} Resolved when the operation is successful and the certificate is pinned. Rejected if certificateFilename is undefined, not found or is not in DER format.

reloadApp
reloadApp()
Reloads the application It can be used to recover an application from errors. It is preferable to avoid using it and to use alternative error handling mechanisms instead. The method is mainly available for compatibility with earlier versions.

removeGlobalHeader
removeGlobalHeader(headerName)
Parameters:
headerName - Mandatory. The name of the header to be removed.
Deprecated:
Since version 8.0 Removes the global HTTP header added by the WL.Client.addGlobalHeader API call
Example:
WL.Client.removeGlobalHeader("MyCustomHeader");

setCookie
setCookie(cookie)
Adds a cookie to the native HTTP client. This function is asynchronous and returns a promise.
Parameters:
cookie - Mandatory. JSON object with required cookie properties: name, value, domain, path, expires
Returns:
Promise
Example:
WL.Client.setCookie(myCookie).then(successFlow);

setDeviceDisplayName
setDeviceDisplayName(deviceDisplayName, options)
Sets the display name of the device. The display name is stored in the MobileFirst Server registration data.
Parameters:
{String} deviceDisplayName - The device display name to set.
{Object} options - An object that contains onSucess and onFailure completion callback functions.

setHeartBeatInterval
setHeartBeatInterval(interval)
Sets the interval of the heartbeat signal. Sets the interval of the heartbeat signal sent to the MobileFirst Server to the specified number of seconds. The heartbeat is used to ensure that the session with the server is kept alive when the app does not issue any call to the server.
Parameters:
interval - Mandatory. An integer value, denoting the interval in seconds between heartbeat messages automatically sent by WLClient to the MobileFirst Server.
An interval value of -1 disables the heartbeat:
WL.Client.setHeartBeatInterval(-1)

setSharedToken
setSharedToken(Object)
Saves a key/value pair such that it is available to other applications. This function saves a key/value pair such that it is available to other applications participating in simple shared data who are in the same application family, defined by the same family name and same application signing key. This API call is only applicable in Android and IOS environments. It is a safe, but no-op, call in other environments.
Parameters:
Object - Mandatory. Object containing the key/value pair to share, like {key: 'myKey', value: 'myValue'}
Returns:
Promise

© Copyright IBM Corp. 2011, 2016.