Skip to content

Visitor JavaScript Api

Requirements and general usage

1
2
// Asynchronous API call
_giosg("visitor", "submit", { username: "John Doe" });
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// Normal API call
function success() {
  console.log("Success!");
}
function error(e) {
  console.log("Error: ", e);
}

// Wait for giosg client to fully load
_giosg(function () {
  // Following is equivalent of:
  // _giosg('visitor', 'submit', { username: 'John Doe' });
  giosg.api.visitor.submit({ username: "John Doe" }).then(success, error);
});

To use giosg visitor JavaScript API you need to be using latest version of giosg script tag on the site.

The best practice is to include giosg script at the start of the HTML document. This is not necessary but is advised so that the _giosg object is available as soon as possible.

JavaScript API can be used in two ways. Asynchronously with _giosg object or calling API method's directly. _giosg object is available right after giosg script tag so you don't need to wait for giosg to be fully loaded before calling API.

Sometimes it is however useful to know when the API calls complete. For that reason you can also call giosg API methods directly and receive jQuery promise as return value. When you want to call API methods directly it is important to wrap your code inside _giosg(function () { ... }); to make sure that giosg client is fully loaded before the call is made.

Following API calls are identical:

1
_giosg('visitor', 'submit', <visitor_data>, <signing_algorithm>, <replace_existing>, <room_information>);

AND

1
_giosg(function () { giosg.api.visitor.submit({ username: 'John Doe' }).then(success, error); });

This documentation uses only asynchronous versions of API's as examples from this point on. To "convert" asynchronous call to normal API call use following pattern:

_giosg('module', 'method', arg1, arg2, ..) translates to giosg.api.<module>.<method>(arg1, arg2, ..);

Visitor variable API

You can attach key value pairs to visitor with giosg JavaScript API. This data is then available to operators in giosg console and also in reporting. Data can also be signed so that you can trust that the submitted data originated from you and was not tampered by visitor.

Visitor variables are available via API as well. See Room visitor variables for more information.

Submit visitor variables

1
2
3
4
5
6
7
// Attach data to visitor
const variables = {
  username: "John Doe",
  age: 29,
  has_car: true,
};
_giosg("visitor", "submit", variables, "plain", true, { name: "My room" });

Javascript call:

_giosg('visitor', 'submit', <variables>, <signing_algorithm>, <replace_existing>, <room_information>);

Attribute Type Required Description
variables object required JSON serializable object containing key value pairs. Object can contain attributes of any names. username and avatar attributes have special meaning. The username is displayed as visitor's name in chat dialog and reports. Example: { username: 'John Doe' }. The avatar variable contains url for image that is then displayed in giosg with the visitor's username. Example { avatar: 'https://example.com/test.png' }. Prefixing variable name with double underscore (__example) makes it hidden in user interface.
signing_algorithm string optional String identifying which algorithm is used for signing. Default is 'plain' which means no signing. See full list of supported algorithms below.
replace_existing boolean optional If set to true will replace existing data that was attached to visitor. Otherwise existing data will be extended with new values. Default is false.
room_information array optional Array of room information objects. This parameter controls the room where the data will be connected. If not set, it will default to domain room. Room info object has to contain either id or name attribute. Example: [{ name: 'My custom room' }]

Special variable names

There are few special cases with variable names.

  • If variable is named username it will be shown as a visitors name in the Giosg UI.
  • If variable is named avatar and contains valid url, that will be used as a visitors avatar image in Giosg UI.
  • If variable name is prefixed with double underscore, it will not be rendered to Giosg UI. This is usefull if you want to for example store some JSON object to visitor variables for system use. Example __im_hidden_variable.

Submit visitor variables to multiple rooms at once

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
// Attach variables to visitor and make it available on multiple rooms.
var roomInfo = [
  {
    id: "kbio5de27gjo767wcqaafh7g6mpluvar4ofiausuac7acbam",
  },
  {
    name: "Another room",
  },
];
_giosg(
  "visitor",
  "submit",
  {
    username: "John Doe",
    age: 29,
    has_car: true,
  },
  "plain",
  true,
  roomInfo
);

It is possible to submit variables to multiple rooms at once by passing array as <room_information> parameter.

Javascript call:

_giosg('visitor', 'submit', <variables>, <signing_algorithm>, <replace_existing>, [<room_information>]);

Signing visitor variables

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// Example of submitting JWT signed visitor data
var jwt_payload =
  "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjb21pY191cmwiOiJodHRwOi8veGtjZC5jb20vMTM2MC8ifQ.BsjBt9a9imoj9P5_7aIAe5nuhPd5jb8HGvAJKPCwm6A";
var algorithm = "HS256";
_giosg("visitor", "submit", jwt_payload, algorithm);

// Example of submitting SHA1/MD5 signed visitor data
var payload = {
  username: "Django signed",
  email: "django@giosg.com",
  _checksum: "e584526251c396fc937e27561c9597c8",
  _exp: "1371720939",
};
_giosg("visitor", "submit", payload, "md5", true);

Signing is used for validating that variables are not altered by web page's visitor. If signing is required for domain and checksum is not set or it's wrong, then giosg will reject the variables and HTTP status 400 will be returned.

There is two different options for signing variables: JSON Web Token specification (JWT) and simple sha1/md5. JSON Web Token specification is recommended with HMAC SHA-256 hash algorithm.

Please note that signed variables can be still seen by visitor but cannot be modifed anyway without giosg being able to recognize that and then reject the variables.

Javascript call:

_giosg('visitor', 'submit', <jwt_payload>, <signing_algorithm>);

jwt_payload is json web token generated from payload data. Note that payload data may contain property exp that contains token expiration time as a UTC UNIX timestamp (an int). This will be used to check if token is still valid.

signing_algorithm is algorithm used. This is required.

Supported signing algorithms

Algorithm Type Description
HS256 JWT  HMAC using SHA-256 hash algorithm (recommended)
HS384 JWT  HMAC using SHA-384 hash algorithm
HS512 JWT  HMAC using SHA-512 hash algorithm
RS256 JWT  RSASSA-PKCS1-v1_5 signature algorithm using SHA-256 hash algorithm
RS384 JWT  RSASSA-PKCS1-v1_5 signature algorithm using SHA-384 hash algorithm
RS512 JWT  RSASSA-PKCS1-v1_5 signature algorithm using SHA-512 hash algorithm
sha1 hash SHA-1 (Secure Hash Algorithm 1)
md5 hash MD5 message-digest algorithm

Generating signed payload with JWT

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
# 1. Install PyJWT
# 2. open python shell and run:
>>> import jwt
>>> import time
>>> exp = int(time.time() + 30) # 30 seconds in future
>>> payload = { "comic_url": "http://xkcd.com/1360/", "exp": exp }
>>> token = jwt.encode(payload, "supersecretkey", "HS256")
>>> print token
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjb21pY191cmwiOiJodHRwOi8veGtjZC5jb20vMTM2MC8ifQ.BsjBt9a9imoj9P5_7aIAe5nuhPd5jb8HGvAJKPCwm6A'
>>>

Example of generating JWT token with Python can be found from the right.

You can find more information about JWT from these resources:

Generating signed payload with SHA1/MD5

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# Open python shell and run:
>>> import hashlib
>>> secret_key = 'supersecret'
>>> payload = { 'username': 'John Doe', 'age': 29 };
>>> sorted_keys = sorted(payload.keys(), key=str.lower)
>>> concatenated_payload = ''
>>> for k in sorted_keys:
>>>     concatenated_payload += '%s:%s&' % (k, payload[k])
>>> concatenated_payload += secret_key
>>> checksum = str(hashlib.md5(concatenated_payload).hexdigest())
>>> print checksum
'0ea59ee5af5fa0aba76f1a6fd209d396'
>>>

Checksum is calculated on server side by using md5 or sha1 algorithm. For checksum calculation payload data need's to be formatted in specific way as a string. First JSON paylod parameters must be sorted alphabetically. Then every parameter and it's value need's to be delimited with :. Delimiter between multiple key/value pairs is &. Then checksum need's to be calculated from that string and appended secret key.

After calculation checksum need's to be placed inside payload JSON in _checksum field. It is also recommended that _exp field is present on payload and contains checksum expiration time as a UTC UNIX timestamp (an int).

Note: Boolean values should be lower case if present. For example checkbox:true. Null values are not recommended.

Example of generating md5 checksum with Python can be found from the right.

Remove submitted variables

These functions will delete the variables only from domain room by default.

1
2
3
4
5
// Remove single key from visitor variables
_giosg("visitor", "remove", "username");

// Clear all variables from visitor
_giosg("visitor", "removeAll");

It is also possible to remove submitted data from visitor.

Remove single variable key from visitor:

_giosg('visitor', 'remove', <key>);

Attribute Type Required Description
key string required Attribute from previously submitted variables that should be removed.

Remove all previously added variables from visitor:

_giosg('visitor', 'removeAll', <room_information>);

Attribute Type Required Description
room_information array optional Array of room information objects. This parameter tells which rooms the variables will be removed from. If not set, it will default to domain room. Room info object has to contain either id or name attribute. Example: [{ name: 'My custom room' }]

Visitor identifier API

You can assign your own custom identifier for the visitor. This identifier should be unique to the visitor. This identifier can also be unique for each visit. Multiple identifier can point to the same visitor.

At the moment this identifier is required if you want to track offline goal conversion.

Attribute Type Required Description
identifier string required Custom identifier for the visitor

Javascript method signature

_giosg('visitor', 'setIdentifier', <identifier>);

1
2
3
4
5
// Set identifier customer-0123456 to the visitor
_giosg("visitor", "setIdentifier", "customer-0123456");

// Set another for the same visitor. Both identifiers can now be used to
_giosg("visitor", "setIdentifier", "other-identifier-1234");

Visitor rooms API

With javascript rooms API you can control which rooms visitor will be connected to.

Join visitor to a room

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// Join visitor to room with room ID
var roomInfo = { id: "6d8b3520-9384-11ed-a80e-0242ac1100271" };
_giosg("room", "join", roomInfo);

// Join visitor to room with room name
var roomInfo = { name: "Special room" };
_giosg("room", "join", roomInfo);

// Join visitor to multiple room's with once call
var roomInfo = [
  {
    id: "6d8b3520-9384-11ed-a80e-0242ac1100271",
  },
  {
    name: "Sales",
  },
];
_giosg("room", "join", roomInfo);

Javascript call:

_giosg('room', 'join', <room_information>);

Attribute Type Required Description
room_information array required Array of room information objects. This parameter controls what rooms visitor will join to. Room info object has to contain either id or name attribute. Example: [{ name: 'My custom room' }]

Leave visitor from room

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
// Leave visitor from room by id
var roomInfo = {
  id: "6d8b3520-9384-11ed-a80e-0242ac1100271",
};
_giosg("room", "leave", roomInfo);

// Leave visitor from room by name
var roomInfo = {
  name: "Support room",
};
_giosg("room", "leave", roomInfo);

// Leave visitor from all rooms expect domain room.
_giosg("room", "leave");

Javascript call:

_giosg('room', 'leave', <room_information>);

Attribute Type Required Description
room_information array optional Array of room information objects. This parameter controls what rooms to leave. If not set, visitor will leave all rooms expect domain room. Room info object has to contain either id or name attribute. Example: [{ name: 'My custom room' }]

Get joined rooms

1
2
3
// Return all joined rooms ids in array.

_giosg("room", "getJoinedRooms");

Visitor chat API

With javascript chat API it is possible to force ending of chat conversation and/or hiding a chat window if a visitor for example logs out from your application.

End chat session

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
// Close all open chats for this visitor from rooms where visitor has joined at the moment.
// Note that chats are closed only from rooms where visitor has joined at the moment and if you need to
// close chat even without visitor joining that room, you need to use "id" parameter.
_giosg("chat", "close", { all: true });
// or
_giosg("chat", "close");

// Close all open chats for this visitor and hide the visitor's chat window
_giosg("chat", "close", { hide: true });

// Close specific chat session with it's room ID.
// This can be used to close chat even if the visitor is not joined to that room
// at the moment.
var opts = {
  id: "12345689-1234-5678-9012-345678901234",
};
_giosg("chat", "close", opts);

// Close chat from specific parent room with room name
// This can be used to close chat even if the visitor is not joined to that room
// at the moment.
_giosg("chat", "close", { name: "Sales room" });

// You can also show a message to user, specify "sender"
// of this message and clear existing history.
var roomData = {
  message: "Chat conversations has ended!",
  messageSender: "Chat service",
  clearHistory: true,
};
_giosg("chat", "close", roomData);

Javascript call:

_giosg('chat', 'close', <options>);

Attribute Type Required Description
options object optional Options object. See possible option values below

Possible attributes for options object:

Option Type Required Description
all boolean optional If set to true, close all open chat sessions from rooms where visitor has joined at the moment.
hide boolean optional If set to true, hides chat window also.
id string optional ID of the room where to close the chat session from. Closes chat from given room even if visitor is not currently joined to that room.
name string optional Name of the room where to close the chat session from. Closes chat from given room even if visitor is not currently joined to that room.
clearHistory boolean optional If set to true, clear's all visitors chat history. This doesn't remove data from database but from client only!
message string optional Show a message to user when chat session is closed
messageSender string optional Set sender of the message. This option only applies if message is specified also.

Hide chat

1
2
3
4
5
6
// Close chat window
_giosg("chat", "hide");

// Close chat window without affection other tabs
// where chat window might be open.
_giosg("chat", "hide", { preserveWindowState: true });

Hide a chat from a visitor without closing the chat session.

Javascript call:

_giosg('chat', 'hide', <options>);

Attribute Type Required Description
options object optional Options object. See possible option values from below.

Possible attributes for options object:

Option Type Description
preserveWindowState object If preserveWindowState is set to true will not affect other tabs where window might be open.

Start task

1
2
3
4
5
6
7
8
// Start a new task
giosg.api.chat.startTask({ message: "This is a task text" });

// Start a new task from anonymous visitor
giosg.api.chat.startTask({ message: "This is a task text" }, undefined, true, {
  username: "My name",
  avatar: "https://....",
});

Starts a new chat with type=task

Javascript call:

giosg.api.chat.startTask(initialMessage, roomId, isAnonymous, visitorVariables)

Attribute Type Required Description
initialMessage object mandatory First message in task
roomId string optional Room which will have this task
isAnonymous boolean optional If true, then use temporarely visitorCid for this task
visitorVariables object optional An object which contants visitor varibles

Return value is promise-like which resolves into {id: "created-chat-id"} object.

Webrtc calls API

This API is available only if organization has "Webrtc calls" feature(s).

Start webrtc call

1
2
3
4
5
6
// start a new call
giosg.api.call.start(
  "Operator name",
  "https://example.com/avatar.png",
  "audio+video"
);

Starts a new task with call_request message. A phone interface will be displayed to visitor.

Javascript call:

`giosg.api.call.start(operatorName, operatorAvatarUrl, kind, roomId)``

Attribute Type Required Description
operatorName string mandatory Name of operator which will be shows in phone interface
operatorAvatarUrl string optional A link to operator avatar
kind string optional Can be 'audio', 'video' or 'audio+video'
roomId string optional Room which will have this task

Return value is promise-like which resolves when task is created.

Goal Match API

If you want to match goals manually instead of automatic detection configured in the Goal UI you can use the Goal Match API to do that.

You can see exact Javascript calls for matching each goal from the Goal UI.

Attribute Type Required Description
goal_id string required ID of the goal that is being matched
options object optional Options for the goal, see below

Options that the matching goal can receive

Attribute Type Required Description
value float optional Value for the goal. If no value is given when goal is matched then configured default value for the goal is used.

Method signature: _giosg('goal', 'matches', <goal_id>, <options>);

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Given that you have created a goal
// with id `2870f654-c6a7-11e6-8a67-60f81db030fe`

// Match a goal that uses the default value
_giosg("goal", "matches", "2870f654-c6a7-11e6-8a67-60f81db030fe");

// Give the goal value when matching the goal for this visitor
_giosg("goal", "matches", "2870f654-c6a7-11e6-8a67-60f81db030fe", {
  value: 1000.1,
});