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 theZAFClient
object.
<脚本type="text/javascript"src="https://static.zdassets.com/zendesk_app_framework_sdk/2.0/zaf_sdk.min.js">脚本>
TheZAFClient
object has the following method:
ZAFClient.init()
Returns aclient
object.
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 thetype
ticket field, you could callclient.get('ticketField:type.options')
.
Arguments
paths
an 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' }
});
// 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处理程序
the handler you want to test
varclient=ZAFClient.init();
client.on('app.registered',functionappRegistered(e){
// do stuff
});
client.has('app.registered',appRegistered);// true
client.has('app.activated',appRegistered);// false
client.instance(guid)
在itialize aZAFClient
for 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 ofZAFClient
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 thetop_bar
andticket_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:
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 loaded
topBarClient.invoke('popover');
});
client.invoke(name [, ...args])
client.invoke(obj)
Executes an action identified by thename
path parameter, or multiple actions defined in theobj
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, callclient.invoke('ticketFields:priority.hide')
.
Arguments
name
the path to callargs
(optional) arguments to be passed to the call, orobj
an 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');
});
// 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 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
name
the name of the event处理程序
the function you attached earlier withon
varclient=ZAFClient.init();
client.on('app.registered',functionappRegistered(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 alsoWorking with framework events.
Arguments
name
the 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 firescontext
(optional) the value ofthis
within 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.registered
event. You can add as many handlers toapp.registered
as you like. They're called immediately after theinit
callback.
client.request(options)
Makes an HTTP request. SeeMaking 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.
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: 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 JavaScriptPromiseobject.
varclient=ZAFClient.init();
client.request('/api/v2/tickets.json').then(
function(tickets){
console.log(tickets);
},
function(response){
console.error(response.responseText);
}
);
// or
varclient=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 callclient.set('ticket.customField:due_date', new Date())
.
Arguments
key
the path to which to set the valueval
, orobj
an 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' }
});
// or
client.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
name
the name of the event you want to triggerdata
(optional) data you want to pass to the handler
varclient=ZAFClient.init();
client.on('activation',function(){
console.log('activating!')
});
client.trigger('activation')// activating!