ZAF Client API

The ZAF client lets your app in the iframe communicate with the host Zendesk product. You can use the client in your apps to listen for events, get or set properties, or invoke actions. The ZAF client also provides additional methods for building apps.

Example:

var client = ZAFClient.init();client.get('ticket.requester.name').then(function(data) {  console.log(data); // { "ticket.requester.name": "Mikkel Svane" }});

ZAFClient Object

When you include the ZAF SDK on your website, you get access to the ZAFClient object.

<script type="text/javascript" src="https://static.zdassets.com/zendesk_app_framework_sdk/2.0/zaf_sdk.min.js"></script>

The ZAFClient object has the following method:

ZAFClient.init()

Returns a client object.

Example:

var client = ZAFClient.init();

Client Object

Methods

client.context()

Requests context for the app, such as the host and location. Depending on the location, the context may provide additional identifiers that you can use with the REST API to request additional data.

Returns

A JavaScript Promise object.

var client = ZAFClient.init();client.context().then(function(context) {  console.log(context);  /*    {      "instanceGuid": "7712c893-bec7-4e00-9db0-87fbb0c12914",      "product": "support",      "account": {        "subdomain": "mondocam"      },      "location": 'ticket_sidebar',      "ticketId": 1234    }  */});

client.get(paths)

Gets data from the UI asynchronously. For a complete list of supported paths, see:

Some path segments can take arguments that you can specify using a colon syntax. For example, to retrieve information about the options available to the type ticket field, you could call client.get('ticketField:type.options').

Arguments
  • paths an array of path strings or a single path string
Returns

A JavaScript Promise object.

var client = ZAFClient.init();
client.get('ticket.subject').then(function(data) {  console.log(data); // { 'ticket.subject': 'Help, my printer is on fire' }});
// or
client.get(['ticket.subject', 'ticket.requester.name']).then(function(data) {  console.log(data); // { 'ticket.subject': 'Help, my printer is on fire', 'ticket.requester.name': 'Mikkel Svane' }});

client.has(name, handler)

Returns whether or not an event has the specified handler attached to it.

Arguments
  • name the name of the event
  • handler the handler you want to test
var client = ZAFClient.init();
client.on('app.registered', function appRegistered(e) {  // do stuff});
client.has('app.registered', appRegistered); // trueclient.has('app.activated', appRegistered); // false

client.instance(guid)

Initialize a ZAFClient for another location.

var client = ZAFClient.init();var otherClient = client.instance('9e012b1f-1397-484e-8810-c444b8085e55');
arguments
  • instanceGuid - the GUID for the desired instance of the app
returns

An instance of ZAFClient for the requested instance GUID

Note that instances are transient in some locations (like ticket sidebar), so if the ticket tab is closed that instance is destroyed.

Example

This example demonstrates how to open a top bar app from a ticket sidebar iframe.

The app in this example must run in the top_bar and ticket_sidebar locations. The manifest would contain a snippet like this:

{  "location": {    "support": {      "ticket_sidebar": "assets/ticket_sidebar.html",      "top_bar": "assets/top_bar.html"    }  }}

The ticket sidebar app runs the following code:

var client = ZAFClient.init();
var topBarClientPromise = client.get('instances').then(function(instancesData) {  var instances = instancesData.instances;  for (var instanceGuid in instances) {    if (instances[instanceGuid].location === 'top_bar') {      return client.instance(instanceGuid);    }  }});
topBarClientPromise.then(function(topBarClient) {  // opens the top bar app, even if its iframe hasn't been loaded  topBarClient.invoke('popover');});

client.invoke(name [, ...args])

client.invoke(obj)

Executes an action identified by the name path parameter, or multiple actions defined in the obj argument, within the product interface. For a complete list of supported paths, see:

Some path segments can take arguments that you can specify using a colon syntax. For example, to hide the priority ticket field, call client.invoke('ticketFields:priority.hide').

Arguments
  • name the path to call
  • args (optional) arguments to be passed to the call, or
  • obj an object containing invoke paths as keys and arrays of arguments as values
Returns

A JavaScript Promise object with the value returned from the method call(s).

var client = ZAFClient.init();
client.invoke('ticket.comment.appendText', 'Help!').then(function() {  console.log('text has been appended');});
// or
client.invoke({  'ticket.comment.appendText': ['Help!'],  'ticketFields:priority.hide': []}).then(function(data) {  console.log(data); // { 'ticket.comment.appendText': value, 'ticketFields:priority.hide': value }});

client.metadata()

Requests metadata for the app, such as the app id, installation id, app plan information, and Stripe subscription id (if applicable).

Returns

A JavaScript Promise object.

var client = ZAFClient.init();
client.metadata().then(function(metadata) {  console.log(metadata);  /*    {      "appId": 123,      "name": "My App",      "installationId": 12345,      "version": "1.0",      "stripe_subscription_id": "sub_1234567890abcdefg",      "plan": {        "name": "starter"      },      "settings": {        "title": "My Installation Name"      }    }  */});

client.off(name, handler)

Allows you to remove a handler for a framework event.

Arguments
  • name the name of the event
  • handler the function you attached earlier with on
var client = ZAFClient.init();
client.on('app.registered', function appRegistered(e) {  // do stuff then remove the handler  client.off('app.registered', appRegistered);});

client.on(name, handler, [context])

Allows you to add handlers to a framework event. You can add as many handler as you wish. They will be executed in the order they were added.

For available events, see:

See also Working with framework events.

Arguments
  • name the name of the framework event you want to listen to. This can be framework, request, or custom events
  • handler a function to be called when this event fires
  • context (optional) the value of this within your handler
var client = ZAFClient.init();client.on('app.registered', function(e) {  // go nuts});

Note: As soon as communication with the framework is established, the SDK triggers an app.registered event. You can add as many handlers to app.registered as you like. They're called immediately after the init callback.

client.request(options)

Makes an HTTP request. See Making API requests from a Zendesk app.

Argument
  • options the url of the resource to request, or an object containing a combination of the following properties with their supported values. All values are case sensitive.
optionsTypeDescription
acceptsObjectMaps a given data type to its MIME type, which gets sent in the "Accept" request header
autoRetryBooleanIf true, overrides the default auto-retry behavior of the request in response to rate-limiting
cacheBooleanIf false, forces requested pages not to be cached by the browser
contentTypeBoolean, StringSpecifies the content type when sending data to a server. If set to false, then no content type header is set. Default value: "application/x-www-form-urlencoded; charset=UTF-8". Example: "application/json"
corsBooleanIf true, makes a request from the browser. If false, makes a request from a Zendesk proxy server. Defaults to false. Requests to Zendesk APIs are always made from the browser, regardless of this option.
crossDomainBooleanIf true, forces a cross-domain request on the same domain
dataObject, String, ArrayData to send to the server. Converted to a query string if not already a string. If you pass a JavaScript object or array and you specify "application/json" as the contentType, use the JSON.stringify() method to ensure the data is a JSON string. For example, data: JSON.stringify( {keyExample: "Value Example"} )
dataTypeStringType of data expected back from the server. Possible values: "text", "json"
headersObjectAdditional header key/value pairs to send along with the request
httpCompleteResponseBooleanFlag to get a full response back, including the headers and the response status. Default value is false
ifModifiedBooleanAllows the request to be successful only if the response has changed since the last request
jwtObjectA JSON web token. See Encoding and sending ZAF JWTs
mimeTypeStringMime type to override the XHR mime type
secureBooleanFlag to allow secure settings to be used
timeoutNumberTimeout period in milliseconds for the request
traditionalBooleanIf true, uses the traditional style of parameter serialization
typeStringThe HTTP method to use. Possible values: "GET", "POST", "PUT", "DELETE", "PATCH"
urlStringUrl of the requested resource
xhrFieldsObjectNative XMLHttpRequest properties, such as withCredentials: true for cross-domain requests

Example:

options: {  accepts: {    text: 'application/x-some-custom-type'  },  autoRetry: true,  cache: false,  contentType: "application/json" ,  data: {    keyExample: "Value Example"  },  dataType: "text"  httpCompleteResponse: true,  type: "GET",  timeout: 200,  url: "www.example.com",  xhrFields: {    withCredentials: true  }}
Returns

A JavaScript Promise object.

var client = ZAFClient.init();
client.request('/api/v2/tickets.json').then(  function(tickets) {    console.log(tickets);  },  function(response) {    console.error(response.responseText);  });
// or
var client = ZAFClient.init();
client.request({  url: '/api/v2/tickets.json',  httpCompleteResponse: true}).then(  function(response) {    console.log(response.responseJSON); // body of the HTTP response    console.log(response.responseText); // body of the HTTP response    console.log(response.status);       // HTTP response status    console.log(response.statusText);   // Is either 'success' or 'error'    console.log(response.headers);      // HTTP response headers  },  function(response) {    console.error(response.responseText);  });

client.set(key, val)

client.set(obj)

Sets data in the UI asynchronously. For a complete list of supported paths, see:

Some path segments can take arguments that you can specify using a colon syntax. For example, to set the due date of a task, you could call client.set('ticket.customField:due_date', new Date()).

Arguments
  • key the path to which to set the value val, or
  • obj an object containing the keys and values to update
Returns

A JavaScript Promise object.

var client = ZAFClient.init();
client.set('ticket.subject', 'Printer Overheating Incident').then(function(data) {  console.log(data); // { 'ticket.subject': 'Printer Overheating Incident' }});
// or
client.set({ 'ticket.subject': 'Printer Overheating Incident', 'ticket.type': 'incident' }).then(function(data) {  console.log(data); // { 'ticket.subject': 'Printer Overheating Incident', 'ticket.type': 'incident' }});

client.trigger(name, [data])

Triggers the specified event on the client.

Arguments
  • name the name of the event you want to trigger
  • data (optional) data you want to pass to the handler
var client = ZAFClient.init();
client.on('activation', function() {  console.log('activating!')});
client.trigger('activation') // activating!