ZAFClient 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:

             
varclient=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 theZAFClientobject.

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

TheZAFClientobject has the following method:

ZAFClient.init()

Returns aclientobject.

Example:

             
varclient=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 JavaScriptPromiseobject.

             
varclient=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 thetypeticket field, you could callclient.get('ticketField:type.options').

Arguments
  • pathsan array of path strings or a single path string
Returns

A JavaScriptPromiseobject.

             
varclient=ZAFClient.init();client.get('ticket.subject').then(function(data){console.log(data);// { 'ticket.subject': 'Help, my printer is on fire' }});// orclient.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
  • namethe name of the event
  • 处理程序the handler you want to test
             
varclient=ZAFClient.init();client.on('app.registered',functionappRegistered(e){// do stuff});client.has('app.registered',appRegistered);// trueclient.has('app.activated',appRegistered);// false

client.instance(guid)

在itialize aZAFClientfor another location.

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

An instance ofZAFClientfor 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 thetop_barandticket_sidebarlocations. 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:

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

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

client.invoke(obj)

Executes an action identified by thenamepath parameter, or multiple actions defined in theobjargument, 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, callclient.invoke('ticketFields:priority.hide').

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

A JavaScriptPromiseobject with the value returned from the method call(s).

             
varclient=ZAFClient.init();client.invoke('ticket.comment.appendText','Help!').then(function(){console.log('text has been appended');});// orclient.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 JavaScriptPromiseobject.

             
varclient=ZAFClient.init();client.元数据().then(function(元数据){console.log(元数据);/*{"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
  • namethe name of the event
  • 处理程序the function you attached earlier withon
             
varclient=ZAFClient.init();client.on('app.registered',functionappRegistered(e){// do stuff then remove the handlerclient.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 alsoWorking with framework events.

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

Note: As soon as communication with the framework is established, the SDK triggers anapp.registeredevent. You can add as many handlers toapp.registeredas you like. They're called immediately after theinitcallback.

client.request(options)

Makes an HTTP request. SeeMaking API requests from a Zendesk app.

Argument
  • optionsthe 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.
options Type Description
accepts Object Maps a given data type to its MIME type, which gets sent in the "Accept" request header
autoRetry Boolean If true, overrides the default auto-retry behavior of the request in response to rate-limiting
cache Boolean If false, forces requested pages not to be cached by the browser
contentType Boolean, String Specifies 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"
cors Boolean If 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.
crossDomain Boolean If true, forces a cross-domain request on the same domain
data Object, String, Array Data 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 thecontentType, use theJSON.stringify()methodto ensure the data is a JSON string. For example,data: JSON.stringify( {keyExample: "Value Example"} )
dataType String Type of data expected back from the server. Possible values: "text", "json"
headers Object Additional header key/value pairs to send along with the request
httpCompleteResponse Boolean Flag to get a full response back, including the headers and the response status. Default value is false
ifModified Boolean Allows the request to be successful only if the response has changed since the last request
jwt Object A JSON web token. SeeEncoding and sending ZAF JWTs
mimeType String Mime type to override the XHR mime type
secure Boolean Flag to allow secure settings to be used
timeout Number Timeout period in milliseconds for the request
traditional Boolean If true, uses the traditional style of parameter serialization
type String The HTTP method to use. Possible values: "GET", "POST", "PUT", "DELETE", "PATCH"
url String Url of the requested resource
xhrFields Object NativeXMLHttpRequest properties, such aswithCredentials: truefor 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 JavaScriptPromiseobject.

             
varclient=ZAFClient.init();client.request('/api/v2/tickets.json').then(function(tickets){console.log(tickets);},function(response){console.error(response.responseText);});// orvarclient=ZAFClient.init();client.request({url:'/api/v2/tickets.json',httpCompleteResponse:true}).then(function(response){console.log(response.responseJSON);// body of the HTTP responseconsole.log(response.responseText);// body of the HTTP responseconsole.log(response.status);// HTTP response statusconsole.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 callclient.set('ticket.customField:due_date', new Date()).

Arguments
  • keythe path to which to set the valueval, or
  • objan object containing the keys and values to update
Returns

A JavaScriptPromiseobject.

             
varclient=ZAFClient.init();client.set('ticket.subject',“打印机过热事件”).then(function(data){console.log(data);// { 'ticket.subject': 'Printer Overheating Incident' }});// orclient.set({'ticket.subject':“打印机过热事件”,'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
  • namethe name of the event you want to trigger
  • data(optional) data you want to pass to the handler
             
varclient=ZAFClient.init();client.on('activation',function(){console.log('activating!')});client.trigger('activation')// activating!