Javascript API

Our documentation to help you customize Olark to fit your website

API Functions

Attention Grabber
Attention Grabber animation CalloutBubble_slide Attention Grabber image height CalloutBubble_bubble_height Attention Grabber image width CalloutBubble_bubble_width Enable Attention Grabber features_attention_grabber Offline Attention Grabber image CalloutBubble_offline_bubble_image_url Online Attention Grabber image CalloutBubble_bubble_image_url
Chat box appearance
Change Chatbox Position system_hb_position Change Chatbox Size system_hb_chatbox_size Change Font Family system_hb_custom_style_font Change Text Position system_right_to_left Change the Border Radius system_hb_custom_style_corners Change the Color of Visitor Messages system_hb_custom_style_secondary_color Disable the Mobile Chatbox system_hb_disable_mobile Floating Chatbox system_hb_detached Set Dark Theme system_hb_dark_theme Set Theme Color system_hb_primary_color Show as Tab system_hb_show_as_tab Show Button Text system_hb_show_button_text
Chat box behavior
Dynamically change the chatbox language api_box_setLocale Expand the chatbox api_box_expand Hide the chatbox api_box_hide Minimize the chatbox api_box_shrink On chatbox expand api_box_onExpand On chatbox hide api_box_onHide On chatbox minimize api_box_onShrink On chatbox show api_box_onShow Show the chatbox api_box_show
Chat conversation
Change operator group api_chat_setOperatorGroup Offline message sent api_chat_onOfflineMessageToOperator On chatbox load api_chat_onready On conversation start api_chat_onBeginConversation On message to operator api_chat_onMessageToOperator On message to visitor api_chat_onMessageToVisitor On operator command api_chat_onCommandFromOperator On operators available api_chat_onOperatorsAvailable On operators unavailable api_chat_onOperatorsAway Send message to visitor api_chat_sendMessageToVisitor Send operator notification api_chat_sendNotificationToOperator Send visitor notification api_chat_sendNotificationToVisitor
Configure the chat box
Allowed domains system_allowed_domains Configure the default language system_localization Enable Chat Ratings features_feedback Enable Pre-chat Survey features_prechat_survey Expand chatbox on load box_start_expanded Hide the minimize button system_hide_minimize_button Load chatbox in DOM element box_inline Page change notifications system_give_location_to_operator Pre-chat visitor notifications system_disable_default_visitor_information Prevent non-local URL wrapping system_chat_does_not_follow_external_links Set operator group system_group Single page applications system_is_single_page_application Start chatbox hidden box_start_hidden
Google Analytics
Enable Google Analytics features_google_analyics Set Google Analytics ID system_google_analytics_id
Greeter
Enable Greeter features_greeter Notify operators of first-time visitors WelcomeAssist_notify_op_of_new_visitor Set Greeter delay in seconds WelcomeAssist_welcome_delay_in_seconds Set Greeter Welcome Messages WelcomeAssist_welcome_messages Switch on the Greeter WelcomeAssist.welcome_new_visitors
Pre-chat survey
Add a custom prechat survey system_custom_prechat Require email system_require_email Require name system_require_name Require phone number system_require_phone
Targeted Chat
Define Targeted Chat rules api_rules_defineRule
Visitor information
Get visitor details api_visitor_getDetails Update CRM custom fields api_visitor_updateCustomFields Update visitor email api_visitor_updateEmailAddress Update visitor name api_visitor_updateFullName Update visitor nickname api_chat_updateVisitorNickname Update visitor phone api_visitor_updatePhoneNumber Update visitor status api_chat_updateVisitorStatus

We offer a powerful Javascript API that gives you flexibility and control over the behavior of the Olark chat box. You can decide, how, when and where to display the chat box on your site, as well as view and update visitor information.

Debugging

Use the !develop command from the agent console to reveal helpful debug tools on the visitor’s chatbox. This is useful for debugging.

Where to place code

Configuration calls must be used when the chatbox first loads on a page. Put configuration calls before olark.identify:

/* custom configuration goes here (www.olark.com/documentation) */
// ⟶ Your configuration here
olark.identify(‘1234-456-78-9810’);

We encourage developers to write their own JavaScript to extend the Olark functionality on their sites. We’re very excited when we see examples of the API used in creative ways. Let us know if you have an interesting implementation and we may publish it. Email support@olark.com with your creations!

Support

We’ll do our best to help with any questions you have. The API is intended to be self-serve for web developers, so we’re not able to write or debug your own code.

Localization

You can translate the chat box into any language in your text settings and editing the text.

If you need to work with multiple languages, use our API to localize language strings.

Attention Grabber animation

Enables the Attention Grabber slide-out animation.

Animate Attention Grabber on checkout page

If you’d like to reach out to people on your checkout page to ensure you make the sale, or offer a discount, you might wish to animate the Attention Grabber on that page only, to give it extra prominence.

// Check if the page URL contains 'checkout'
if(window.location.href.indexOf("checkout") >= 0){

    // Enable the Attention Grabber
    olark.configure('CalloutBubble.slide', true );

}

When the Attention Grabber slides out, it looks like this:

Screenshot of API call bubble slide

Alternatively, should you enable the slide out action on the Attention Grabber settings page, you can disable this animation per page by switching the true to false in the example above.

Enable the Attention Grabber animation
olark.configure('CalloutBubble.slide', true );

Attention Grabber image height

Set the Attention Grabber image height in pixels.

For example:

olark.configure('CalloutBubble.bubble_height', 25 );

Results in an attention grabber with a height of 25px.

This only works if you either, have the Attention Grabber switched on in the Attention Grabber settings, or are using the API call to Enable the Attention Grabber.

Attention Grabber image height
olark.configure('CalloutBubble.bubble_height', integer );

Attention Grabber image width

Set the Attention Grabber image width in pixels.

For example:

olark.configure('CalloutBubble.bubble_width', 100 );

Results in an attention grabber with a width of 100px.

This only works if you either, have the Attention Grabber switched on in the Attention Grabber settings, or are using the API call to Enable the Attention Grabber.

Attention Grabber image width
olark.configure('CalloutBubble.bubble_width', integer );

Enable Attention Grabber

You can enable the Attention Grabber on a page by page basis using this API call.

Show Attention Grabber on checkout page

If you’d like to reach out to people on your checkout page to ensure you make the sale, or offer a discount, you might wish to show the Attention Grabber on that page only.

// Check if the page URL contains 'checkout'
if(window.location.href.indexOf("checkout") >= 0){

    // Enable the Attention Grabber
    olark.configure('features.attention_grabber', true );

}
else {

    // Otherwise disable the Attention Grabber
    olark.configure('features.attention_grabber', false );

}
Enable the Attention Grabber
olark.configure('features.attention_grabber', true );

Offline Attention Grabber image

Sets the Attention Grabber image while all your operators are set to away or offline.

Like the other Attention Grabber calls, this works on a page by page basis. You can choose an offline Attention Grabber for use across the entire site in the Attention Grabber settings

This call would be useful if you wanted a different image on a particular page, such as the contact page, or if you only wanted the Attention Grabber to appear on one page.

You would add it under the existing Olark code on the page like this:

olark.configure('CalloutBubble.bubble_image_url_offline', 'path/to/file' );
Offline Attention Grabber image
olark.configure('CalloutBubble.bubble_image_url_offline', 'path/to/file' );

Online Attention Grabber image

Sets the Attention Grabber image while your operators are set to available.

Like the other Attention Grabber calls, this works on a page by page basis. You can choose an online Attention Grabber for use across the entire site in the Attention Grabber settings

This call would be useful if you wanted a different image on a particular page, such as the contact page, or if you only wanted the Attention Grabber to appear on one page.

You would add it under the existing Olark code on the page like this:

olark.configure('CalloutBubble.bubble_image_url', 'path/to/file' );
Online Attention Grabber image
olark.configure('CalloutBubble.bubble_image_url', 'path/to/file' );

Change Chatbox Position

Change the position of the chatbox. This can also be changed site wide from the Theme Settings Page.

postition

Change chatbox position
olark.configure('system.hb_position', 'left');

Change Chatbox Size

Change the size of the chatbox. The chatbox can be configured to appear in one of three different sizes: small, medium, or large. By default, it uses the medium size. Changing the size of the chatbox will also modify the size of the chat button.

This configure call will only accept a string value indicating the size you would like to use. For example

olark.configure('system.hb_chatbox_size', 'sm'); // Small

themes chatbox size small

olark.configure('system.hb_chatbox_size', 'md'); // Medium

themes chatbox size medium

olark.configure('system.hb_chatbox_size', 'lg'); // Large

themes chatbox size large

You can also configure the chatbox to take up the full height of the web page and slide in from the side as opposed to the bottom, like a “side drawer”. This configuration uses medium size defaults.

olark.configure('system.hb_chatbox_size', 'dr'); // Side drawer
Change chatbox size
olark.configure('system.hb_chatbox_size', 'sm');

Change Font Family

Choose what font you’d like the chatbox to have. Use this call with an Array of valid loaded fonts. Note that the fonts must be loaded on your site for the chatbox to be able to use them.

olark.configure('system.hb_custom_style', {
  general: {
    fonts: ['Bitter', 'serif'],
    corners: '',
    secondaryColor: ''
  }
});

font

Change the font of the chatbox
olark.configure('system.hb_custom_style', { 
	general: { 
		fonts: ['Bitter', 'serif'], 
		corners: '', 
		secondaryColor: '' 
	} 
});

Change Text Position

Change the text position for right to left language support. This can also be changed site wide from the Theme Settings Page.

Change text position
olark.configure('system.right_to_left', true );

Change the Border Radius

We have two options that allow you to have ‘soft’ or ‘hard’ corners for the chatbox. By default the chatbox will have soft corners.

olark.configure('system.hb_custom_style', {
  general: {
    fonts: [''],
    corners: 'hard',
    secondaryColor: ''
  }
});

corners

Change the border radius for the corners of the chatbox
olark.configure('system.hb_custom_style', { 
	general: { 
		fonts: [''], 
		corners: 'soft', 
		secondaryColor: '' 
	} 
});

Change the Color of Visitor Messages

Change the color of your visitor messages. This configuration key will only accept hex values.

olark.configure('system.hb_custom_style', {
  general: {
    fonts: [''],
    corners: '',
    secondaryColor: '#ffe6ff'
  }
});

secondary color

Change the color of visitor messages
olark.configure('system.hb_custom_style', { 
	general: { 
		fonts: [''], 
		corners: '', 
		secondaryColor: '#ffe6ff' 
	} 
});

Disable the Mobile Chatbox

Disable the mobile chatbox. This can also be changed site wide from the Theme Settings Page.

Disbale the Mobile Chatbox
olark.configure('system.hb_disable_mobile', true );

Floating Chatbox

Normally, the chatbox is anchored to the bottom of the webpage. This detaches the chatbox from the bottom of the page, allowing it to float near the bottom instead.

olark.configure('system.hb_detached', true);

themes

Floating chatbox
olark.configure('system.hb_detached', true );

Set Dark Theme

Choose a light or dark theme for the chatbox. This can also be changed site wide from the Theme Settings Page.

light and dark themes

You can enable a dark theme on a specific page. You can also do this for your entire site from the Theme Settings Page.

Set dark or light theme
olark.configure('system.hb_dark_theme', true );

Set Theme Color

Set the primary color of the chatbox. This can also be changed site wide from the Theme Settings Page.

This configure call will only accept a hex string. For example

olark.configure('system.hb_primary_color', '#744da8');

themes primary color

Set theme color
olark.configure('system.hb_primary_color', string);

Show as Tab

Show the chatbox as a tab. This can also be changed site wide from the Theme Settings Page.

tab

Show as tab
olark.configure('system.hb_show_as_tab', true );

Show Button Text

Show the button text on the chatbox icon. This can also be changed site wide from the Theme Settings Page.

button text

Show button text
olark.configure('system.hb_show_button_text', true );

Dynamically change the chatbox language

You can dynamically change the chatbox language after the page has loaded. By using this call the default localization strings provided by Olark will be used and will override any text you have set in the Text & Forms dashboard. This call, however, will not override any language configuration calls like olark.configure('locale.welcome_title', 'Foo'), the string provided by that call always takes highest priority.

You can see a list of languages we support here.

Screenshot of API call set locale

Dynamically change the chatbox language
olark('api.box.setLocale', 'en-US')

Expand the chatbox

Expands the chatbox to its fully expanded height. It will also show the chatbox if not already visible, in the same way as api.box.show.

Using this API call overrides any existing Targeted Chat rules that may hide the chatbox.

API Screenshot

A classic use of the Javascript API is to make your own click-to-chat button. Clicking this button will show the Olark chatbox and expand it to its maximum height.

To make your own click-to-chat button, add the api.box.expand call as the value for the onclick event:

<a href="javascript:void(0);" onclick="olark('api.box.expand')">
    Click here to chat!
</a>

We have a more detailed click-to-chat tutorial in our help section, including an example of a CSS-only implementation.

Expand the chat box
olark('api.box.expand');

Hide the chatbox

Hides the chatbox. This box will make the chatbox disappear on the page, but operators will still be able to see visitors in their visitor list.

Screenshot of API call hide

Hide the chatbox if not logged in

You might want Olark to be loaded in the background on a particular page, but not show immediately. Here’s how that might look in PHP:

<?php
// Check to see if the user is logged in
if (!$user_logged_in)
{
    // Hide the chat box
    olark('api.box.hide');
}
?>

You can also use our Targeted Chat tool to hide the widget, without altering the code of your website.

Hide the chat box
olark('api.box.hide');

Minimize the chatbox

Minimizes the chatbox. Opposite of api.box.expand.

Screenshot of API call shrink

Click-to-minimize button

If you have your own click to chat button, you might also want to make click to minimize button:

<a href="javascript:void(0);" onclick="olark('api.box.shrink')">
    Minimize chat
</a>
Minimize the chat box
olark('api.box.shrink');

On chatbox expand

Whenever the chatbox is expanded, the given callback function will be triggered.

Screenshot of API call on expand

Watch for visitors clicking the chatbox

A visitor to your site might expand the chatbox, but not initiate a conversation. You can check to see if a conversation has started and if not, send the visitor a message after 3 seconds.

<script>
// Triggers when the chat box has been expanded
olark('api.box.onExpand', function() {

    // Use getDetails to grab visitor information
    olark('api.visitor.getDetails', function(details){

        // isConversing tells you if any messages has been exchanged
        // between the visitor and the operator
        if (!details.isConversing) {

            // Wait 3 seconds (3000 milliseconds)
            setTimeout(function(){

                // Use the API to send the visitor a message
                olark('api.chat.sendMessageToVisitor', {
                    body: "Let me know if you have any questions."
                });

            }, 3000);

        }

    });

});
</script>

Track when visitors expand your Olark widget

If you are trying to track when visitors interact with the Olark widget, to perhaps test out different methods of presenting the widget, you can use this following example to do so.

<script>
olark('api.box.onExpand', function(event) {

    // Example code
     yourAnalytics.track("visitor_expanded_olark");

});
</script>
Monitor when the chat box expands
olark('api.box.onExpand', function() {
	// Your callback function
});

On chatbox hide

Whenever the chatbox is hidden, the given callback function will be triggered.

Screenshot of API call onhide

Notify an operator when a visitor closes the chat box

You can notify your operator that the visitor has closed the chatbox if you have already started chatting:

<script>
// Checks to see if the coversation has started
olark('api.chat.onBeginConversation', function(){

    // Triggers when the chat box has been hidden
    olark('api.box.onHide', function() {

        // Notifies the operator. The visitor does not see this.
        olark('api.chat.sendNotificationToOperator', {body: "Visitor hid the chatbox"})

    });

});
</script>

You could just as easily replace the onHide call, to be onShrink if you wanted to report to the operator when the visitors minimizes the chat widget.

Monitor when the chat box is hidden
olark('api.box.onHide', function() {
	// Your callback function
});

On chatbox minimize

Whenever the chatbox becomes minimized, the given callback function will be triggered.

Screenshot of API call on shrink

Track when visitors minimize your Olark widget

If you are trying to track when visitors shrink the Olark widget, to perhaps track via analytics the efficacy of different auto-messaging rules, you can use this following example to do so.

<script>
olark('api.box.onShrink', function(event) {

    // Example code
     yourAnalytics.track("visitor_minimized_olark");

});
</script>

Notify an operator when a visitor minimizes the chat box

You can notify your operator that the visitor has minimized the widget if you have already started chatting:

<script>
// Checks to see if the coversation has started
olark('api.chat.onBeginConversation', function(){

    // Triggers when the chat box has been hidden
    olark('api.box.onShrink', function() {

        // Notifies the operator. The visitor does not see this.
        olark('api.chat.sendNotificationToOperator', {body: "Visitor shrank the chatbox"})

    });

});
</script>
Monitor for the chat box minimizing
olark('api.box.onShrink', function() {
	// Your callback function
});

On chatbox show

Whenever the chatbox is shown (unhidden), the given callback function will be triggered.

Screenshot of API call on show

Update visitor status when chat box visible

If you have chosen to have your chatbox hidden by default, you can indicate in your buddy list that a visitor can now see the chatbox. This means they might be about to send a message:

olark('api.box.onShow', function() {
    olark('api.chat.updateVisitorNickname', {
        snippet: "is visible"
    });
});
Monitor when the chat box unhides
olark('api.box.onShow', function() {
	// Your callback function
});

Show the chatbox

Shows the chatbox. Showing the chatbox will make it appear on the page. This will override settings such as Invisible Olark.

Screenshot of API call show

Should you wish to show the widget on specific pages, you can also create these rules using our Targeted Chat tool, instead of updating the code on your page.

Show the chatbox on error

If a visitor runs into an error, you might want to make sure that the chatbox is displayed:

<script>
// If you have a script that returns error codes, show the Olark chatbox
if (errorOnPage) {
    olark('api.box.show');
}
</script>
Unhide the chat box
olark('api.box.show');

Change operator group

Note: This method requires a plan that supports the Groups feature.

Locks the visitor to a specific group of operators. All messages from the visitor will now go to that group of operators instead of all operators. See the operator configuration page to find the Group ID.

Choose operator group by button click

When the visitor clicks the Talk to our Sales Team button, lock to the Sales Group specifically.

<script>
    document.getElementById('talk-to-sales').onclick = function() {

        olark('api.chat.setOperatorGroup', {
            group: 'abcdef123456'
        });

        olark('api.box.expand');

    }
</script>

This example assumes that the Sales Group ID is ‘abcdef123456’. You can find the Group ID on the operator configuration page.

Switch to a backup operator group

This is a special rule that notifies a backup group of operators when a customer initiates a conversation but doesn’t receive a response within a minute.

Note: This script may not work well without routing to ALL operators enabled in the Setup page.

<script>
// Creates a new Targeted Chat rule
olark('api.rules.defineRule', {

    id: '44',
    description: "notify backup team if customers aren't responded to within 60 seconds ",
    condition: function(pass) {

        // Retrieve info about the chat
        olark('api.visitor.getDetails', function(details) {

            // Trigger this action if message hasn't been responded to within 60 seconds (NOTE: This will trigger if an operator initiates a message)

            if ((details.messageCountForThisVisit < 2) && (details.secondsSinceLastMessage > 60) && (details.isConversing)) {
                pass();
            }

        });
    },
    action: function() {

        // Change the group to the backup group using their Group ID
        olark('api.chat.setOperatorGroup', {
            group: 'YOURBACKUPGROUPID'
        });

        // Send a notification to the backup group operators
        olark('api.chat.sendNotificationToOperator',
        {
            body: "Visitor has been waiting more than 60 seconds"
        });

    },

    // Trigger the rule page change if customer still hasn't received response
    perPage: true

});
</script>
Lock the visitor to an operator group
olark('api.chat.setOperatorGroup', {
	group: // Group ID from https://www.olark.com/op
});
Arguments
  • options.group
    the Group ID that you want to lock to

Offline message sent

When an offline message is sent to the operator, this will call the given callback with an event object

Track visitors who send you an offline message

Use your favorite analytics software to keep track of visitors who have sent an offline message to an operator (since they might be more valuable):

<script>
olark('api.chat.onOfflineMessageToOperator', function(event) {

    // Example code
    yourAnalytics.track("sent_an_offline_message");

});
</script>

Or, you could send a message back explaining that no-one is around, and point the visitor to your help center

<script>
olark('api.chat.onOfflineMessageToOperator', function(event) {


    olark('api.chat.sendMessageToVisitor', {
        body: "Sorry, we have just gone offline. We'll be back soon. In the meantime, why not check out our <a href="https://olark.com/help>Help Center</a>?"
    });

});
</script>
Monitor for an offline message being sent
olark('api.chat.onOfflineMessageToOperator', function(event) {
	// Your callback function
});
Arguments
  • event.message.body
    the contents of the message

On chatbox load

Use this API call to detect when the Olark chatbox has loaded. You can create your own callback function once the onReady event fires.

For example, you would use onReady if you need to manipulate elements on your page only when you know for sure that Olark has loaded. You might be doing an A/B test for live chat, and want to send an event to your analytics when Olark has loaded on a page.

Check Olark has loaded
olark('api.chat.onReady', function(){
	// Your callback function
});

On conversation start

Whenever a visitor or operator sends the first message, the given callback function will be triggered.

Show premium users in visitor list

Olark already sends some nice information to the operator when the chat first begins, but you can send your own information too. Here’s how you might highlight that a visitor to your site is a premium customer:

<script>
// Triggers when the first message has been sent
// Including automated messages from the Greeter or Targeted Chat rules
olark('api.chat.onBeginConversation', function() {

    // Get the data from your own server as to whether the visitor is a premium account
    if (currentVisitorIsPremium) {

        // Notifies the operator - the visitor does not see this
        olark('api.chat.sendNotificationToOperator', {
            body: "This is a premium customer"
        });

    }

});
</script>

Send an automatic response if an operator does not answer within X seconds

While we encourage you to be as human as possible during your interactions, and avoiding as much canned copy as you can, we do recognize the fact that sometimes something comes up and you cannot answer a visitor’s chat right away. This example will send a response to a visitor after 60 seconds if the operator does not reply:

<script>
var maxMilliseconds = 60*1000; // make sure the visitor doesn't receive a reply within 60 seconds
var replyTimer = null;

olark("api.chat.onMessageToOperator", function() {
    replyTimer = setTimeout(function() {
    replyTimer = null;
    olark("api.chat.sendMessageToVisitor", {
        body: "Sorry! I'm a little busy at the moment but will get back with you soon."
        });
    }, maxMilliseconds);
});

olark("api.chat.onMessageToVisitor", function() {
    if (replyTimer) {
        clearTimeout(replyTimer);
    }
});
</script>
Monitor when a conversation begins
olark('api.chat.onBeginConversation', function() {
	// Your callback function
});

On message to operator

Whenever a message is sent to the operator, this will call the given callback with an event object.

Track messages to operators

Use your favorite analytics system to keep track of visitors who have sent a message to an operator (since they might be more valuable):

<script>
olark('api.chat.onMessageToOperator', function(event) {
    yourAnalytics.track("chatted_with_operator");
});
</script>

Track positive reactions

Maybe you want to keep track of positive vs. negative reactions. You could watch when people send you smileys, indicating that they are happy:

<script>
olark('api.chat.onMessageToOperator', function(event) {
    if (event.message.body.indexOf(":)") != -1) {
        yourAnalytics.track("customer_is_happy");
    }
});
</script>

If these statistics sounds cool to you, you should probably try enabling our Google Analytics plugin for a more in-depth integration with Google Analytics.

Check for a message being sent to the operator
olark('api.chat.onMessageToOperator', function(event) {
	// Your callback function
});
Arguments
  • event.message.body
    the contents of the message

On message to visitor

Whenever a message is sent to the visitor, this will call the given callback with an event object.

Track operator response times

Use your favorite analytics system to keep track of how long it takes an operator to respond to a visitor:

<script>
olark('api.chat.onMessageToOperator', function(event) {

    // Get the timestamp for when the visitor sends a message
    var visitorSentAt = +new Date;

    olark('api.chat.onMessageToVisitor', function(event) {


        // Get the timestamp for when the operator sends a message
        var operatorSentAt = +new Date;

        // Calculate the difference between the two times and track the event
        // Check your anayltics software API to see how to push an event
        yourAnalytics.track("operator_response_time", operatorSentAt - visitorSentAt);

    });

});
</script>

If these statistics sounds cool to you, you should probably try enabling our Google Analytics for a more in-depth integration with Google Analytics.

Check for a message being sent to the visitor
olark('api.chat.onMessageToVisitor', function(event) {
	// Your callback function
});
Arguments
  • event.message.body
    the contents of the message
  • event.message.nickname
    the display name of the operator

On operator command

Whenever a command is sent from the visitor, e.g. !track this is a lead, this will call the given callback with an event object.

Commands must begin with an exclamation point ! and come at the start of a message. You can also see a list of the default operator commands in our help section. To see these while chatting, type !help into a chat at any time to see the list of commands you can perform. Your visitors will not see the command unless specified.

Push the visitor to your FAQ page

Use the command !faq to send a visitor to your FAQ page:

<script>
olark('api.chat.onCommandFromOperator', function(event) {

    // Checks for the !faq command
    if (event.command.name == 'faq') {

        // Let the customer know what you're about to do
        olark('api.chat.sendMessageToVisitor', {
            body: "Let me point you to our FAQ page"
        });

        // Redirect the visitor's browser to your FAQ page
        window.location = "http://www.example.com/pages/faq"

    }

});
</script>

Add an optional piece of information

Create a custom command to notify a new chatter that there is a queue. By using !q and adding an integer, such as 2 after it, !q 2, you add a custom time into the message. This example tells the visitor that the operator will be with them in 2 minutes. If the operator entered !q 3, it would say 3 minutes. This example also tells the operator what has been sent.

<script>
olark('api.chat.onCommandFromOperator', function(event) {

    // Checks for the !q command
    if (event.command.name == 'q') {

        // Let the customer know what you're about to do
        olark('api.chat.sendMessageToVisitor', {
        body: "Hi there, chat is really busy, I'll be with you in " + (event.command.body) + " minutes"
        });

        olark('api.chat.sendNotificationToOperator', {
        body: "Telling customer you will be with them in " + (event.command.body) + " minutes"
        });

    }

});
</script>

Make a comment to follow up with a visitor

Create a custom followup command to add some notes about following up with this customer to your CRM:

<script>
olark('api.chat.onCommandFromOperator', function(event) {

    // Checks for the !comment command
    if (event.command.name == 'comment') {

        // This is an example of how you might send the event to your CRM
        // Check out the API of your CRM provider to see how to do this
        yourCRM.addNoteToCustomer(event.command.body);

    }

});
</script>
Monitor for an operator using a command
olark('api.chat.onCommandFromOperator',
	function(event) {
		// Callback function
	}
);
Arguments
  • event.command.body
    the contents of the message, e.g. 'this is a lead' (optional)
  • event.command.name
    the name of the command, e.g. 'track' (required)

On operators available

Whenever any operator comes online, the given callback will be triggered.

Indicate you have operators available

Show a green icon whenever you have operators available to chat, or a red one when you are away:

<!-- HTML element to show chatbox status -->
<div id="chat-indicator">Live chat</div>

<style type="text/css">

    /* Operators available */
    .green-icon {
        background-color: green;
    }

    /* Operators offline */
    .red-icon {
        background-color: red;
    }

</style>

<script>
olark('api.chat.onOperatorsAvailable', function() {

    // Identify the element, and give it a class name
    document.getElementById('chat-indicator').className = 'green-icon';

});
olark('api.chat.onOperatorsAway', function() {

    // Identify the element, and give it a class name
    document.getElementById('chat-indicator').className = 'red-icon';

});
</script>

Here is an example of what it might look like with a little styling. In this example, we also added selectors to change the text as well as the color.

<style type="text/css">

    /* Operators available */
    .green-icon {
    background-color: green;
    }
    .green-icon::after {
        content: ": on";
    }

    /* Operators offline */
    .red-icon {
    background-color: red;
    }
    .red-icon::after {
        content: ": off";
    }
</style>

Screenshot of API call on Operators Available

Please note: This call will only fire if an operator’s state changes. It cannot be queried.

Trigger for when operators are available
olark('api.chat.onOperatorsAvailable', function() {
	// Your callback function
});

On operators unavailable

Whenever all operators are offline, the given callback will be triggered.

Indicate your operators are offline

Show a red icon whenever you have operators available to chat:

<!-- HTML element to show chatbox status -->
<div id="chat-indicator">Live chat</div>

<style type="text/css">

    /* Operators available */
    .green-icon {
        background-color: green;
    }

    /* Operators offline */
    .red-icon {
        background-color: red;
    }

</style>

<script>
olark('api.chat.onOperatorsAvailable', function() {

    // Identify the element, and give it a class name
    document.getElementById('chat-indicator').className = 'green-icon';

});
olark('api.chat.onOperatorsAway', function() {

    // Identify the element, and give it a class name
    document.getElementById('chat-indicator').className = 'red-icon';

});
</script>

Here is an example of what it might look like with a little styling. In this example, we also added selectors to change the text as well as the color.

<style type="text/css">

    /* Operators available */
    .green-icon {
    background-color: green;
    }
    .green-icon::after {
        content: ": on";
    }

    /* Operators offline */
    .red-icon {
    background-color: red;
    }
    .red-icon::after {
        content: ": off";
    }
</style>

Screenshot of API call on Operators Available 2

Please note: This call will only fire if an operator’s state changes. It cannot be queried.

Trigger for when operators are away
olark('api.chat.onOperatorsAway', function() {
	// Your callback function
});

Send message to visitor

Send a message to the visitor. It will appear as if the message came from an operator.

Trigger an automated message

Send a welcome message whenever a visitor clicks on a help me button:

<!-- HTML button -->
<a id="help-me" href="#">Live chat help</a>

<script>
document.getElementById('help-me').onclick = function() {

    olark('api.chat.sendMessageToVisitor', {
        body: "Let me know if you have any questions."
    });

    // Stops the link reloading the page
    return false;

}
</script>
Send a message to the visitor
olark('api.chat.sendMessageToVisitor', options );
Arguments
  • options.body
    the contents of the message to send the visitor

Send operator notification

Send a notification message to the operator. The operator will see [info] to indicate that this message was not sent from the visitor.

Notify operator on landing pages

You can send your operator a notification when the visitor lands on a particular page, such as a landing page:

<script>
// Checks if the current URL contains 'landing'
if (document.location.href.indexOf('landing') != -1) {

    olark('api.chat.sendNotificationToOperator',
    {

        // Send a custom notification
        body: 'visitor landed on the billing page'

    });

}
</script>

Notify operators on landing pages after one minute

Perhaps you want to notify an operator when a visitor is hesitating on a page for more than 60 seconds, so you can choose to initiate a chat with them:

<script>
// Create a timer
setTimeout(function(){

    olark('api.chat.sendNotificationToOperator',
    {

        // Send a custom notification
        body: 'this visitor is hesitating'

    });

// Set time to 60 seconds (60000 milliseconds)
}, 60000);
</script>
Send a notification to the operator
olark('api.chat.sendNotificationToOperator', {
	body: string
});
Arguments
  • options.body
    the contents of the notification to send the operator

Send visitor notification

Send a notification message to the visitor. The message will look like a notification, and will not show up as coming from a particular operator.

Notify a visitor if no immediate response

Assure a visitor that the operator will be back later if there is no response from an operator in 60 seconds:

<script>
// Set a timer variable
var lastMessageTimeout;

// Wait for a message to the visitor
olark('api.chat.onMessageToVisitor', function(){

    // If a message is sent, reset the timer
    clearTimeout(lastMessageTimeout);

    // Start the timer
    lastMessageTimeout = setTimeout(function(){

        // Send a custom notification to the visitor
        olark('api.chat.sendNotificationToVisitor',
        {
            body: "the operator just stepped out for a moment"
        })

    // Set timer to one minute (60,000 milliseconds)
    }, 60000);

});
</script>
Send a notification to the visitor
olark('api.chat.sendNotificationToVisitor', {
	body: string
});
Arguments
  • options.body
    the contents of the notification to send the visitor

Allowed domains

Set which domains the chatbox will be displayed on. If your website spans multiple domains' subdomains, you can choose which subdomains will work.

Note that chats cannot continue across top-level domains. In order for chats to go from a top-level domain to a subdomain, the top-level domain cannot be a naked domain (i.e. the URL should be http://www.example.com, not http://example.com).

Use * as a wildcard. Separate multiple domains with commas, e.g. *.yourdomain.com,*.yourotherdomain.com.

/* custom configuration goes here (www.olark.com/documentation) */
olark.configure('system.allowed_domains', '*.yourdomain.com,*.yourotherdomain.com');

You can also add subdomains on your Setup page page.

Set allowed domains
olark.configure('system.allowed_domains', string);

Configure the default language

You can change the language of the chatbox per page by using the following configuration call. If you want to change the language of the chatbox site wide you can do so from your Text & Forms settings. We support the following languages.

olark.configure("system.localization", "en-US"); // English (United States)
olark.configure("system.localization", "de-DE"); // Deutsch (Deutschland)
olark.configure("system.localization", "es-ES"); // Spanish (Spain)
olark.configure("system.localization", "fr-FR"); // Français (France)
olark.configure("system.localization", "it-IT"); // Italian (Italy)
olark.configure("system.localization", "nl-NL"); // Dutch (Netherlands)
olark.configure("system.localization", "pt-BR"); // Portuguese (Brazilian)
olark.configure("system.localization", "ru-RU"); // Russian (Russia)
olark.configure("system.localization", "sv-SE"); // Swedish (Sweden)
olark.configure("system.localization", "tr-TR"); // Turkish (Turkey)
olark.configure("system.localization", "zh-CN"); // Simplified Chinese (China)

Note that by using the system.localization call our default localization strings will be used. If you’d like more granular control over chatbox strings check out our article on Changing the chatbox language. Here are all the strings you can configure:

/* online chatbox strings */  
olark.configure("locale.welcome_title", "Chat with us");
olark.configure("locale.chatting_title", "Chat with us");
olark.configure("locale.welcome_message", "Have a question? We'd love to help.");
olark.configure("locale.chat_input_text", "Type a message...");
olark.configure("locale.ended_chat_message", "Have a question? This conversation has ended. You can start a new chat by sending another message if you like. Thanks for stopping by to chat with us. Come back again anytime.");

/* offline chatbox strings */
olark.configure("locale.unavailable_title", "Need help?");
olark.configure("locale.away_message", "We're not around but please leave us a message");
olark.configure("locale.name_input_text", "Click here and type your name");
olark.configure("locale.email_input_text", "Click here and type your email");
olark.configure("locale.phone_input_text", "Click here and type your phone number");
olark.configure("locale.offline_note_message", "Have a question about Olark live chat or a Support Query? To speed up the process please give us as much info about your issue as you can. ");
olark.configure("locale.send_button_text", "Send");
olark.configure("locale.offline_note_thankyou_text", "Thank you for your message.  We will get back to you as soon as we can.");
olark.configure("locale.offline_note_error_text", "You must complete all fields and specify a valid email address");

/* pre-chat survey strings */  
olark.configure("locale.name_input_text", "<Click here> and type your Name");
olark.configure("locale.email_input_text", "<Click here> and type your Email");
olark.configure("locale.phone_input_text", "<Click here> and type your Phone");
olark.configure("locale.introduction_error_text", "Please leave a name and email address so we can contact you in case we get disconnected");
olark.configure("locale.introduction_messages", "Welcome, just fill out some brief information and click Start Chat to talk to us");
olark.configure("locale.introduction_submit_button_text", "Start chat");

   /* offline message form strings*/
olark.configure("locale.offline_survey_submit_button_text", "Send");
olark.configure("locale.offline_survey_next_button_text", "Next");
olark.configure("locale.offline_survey_thank_you_message", "Thanks for your message! We will have a member of our team contact you shortly.");
olark.configure("locale.offline_survey_welcome_message", "We're not around but we still want to hear from you! Leave us a note:");
olark.configure("locale.offline_survey_name_label", "Name");
olark.configure("locale.offline_survey_name_placeholder", "Enter your name...");
olark.configure("locale.offline_survey_email_label", "Email");
olark.configure("locale.offline_survey_email_placeholder", "Enter your email...");
olark.configure("locale.offline_survey_phone_label", "Phone");
olark.configure("locale.offline_survey_phone_placeholder", "Enter your phone number...");
olark.configure("locale.offline_survey_website_label", "Website");
olark.configure("locale.offline_survey_website_placeholder", "Enter your website...");
olark.configure("locale.offline_required_error_message", "Please complete all required fields");
olark.configure("locale.offline_email_validation_message", "Please enter a valid email address");
olark.configure("locale.offline_phone_validation_message", "Please enter a valid phone number");
olark.configure("locale.offline_website_validation_message", "Please enter a valid URL");

/* greeter strings */
olark.configure("WelcomeAssist.welcome_messages", ["&iexcl;Bienvenidos a nuestro sitio!"]);

/* chat ratings strings */
olark.configure('locale.feedback_survey_question_chat_text', 'How satisfied were you with this chat?');
olark.configure('locale.feedback_survey_question_operator_intelligence_text', 'How knowledgeable was the chat agent?');
olark.configure('locale.feedback_survey_question_operator_speed_text', 'How responsive was the chat agent?');
olark.configure('locale.feedback_survey_question_operator_attitude_text', 'How friendly was the chat agent?');
olark.configure('locale.feedback_survey_question_1_text', 'Question 1 of 5');
olark.configure('locale.feedback_survey_question_2_text', 'Question 2 of 5');
olark.configure('locale.feedback_survey_question_3_text', 'Question 3 of 5');
olark.configure('locale.feedback_survey_question_4_text', 'Question 4 of 5');
olark.configure('locale.feedback_survey_question_5_text', 'Question 5 of 5');
olark.configure('locale.feedback_survey_question_chat_low', 'Not at all satisfied');
olark.configure('locale.feedback_survey_question_chat_high', 'Extremely satisfied');
olark.configure('locale.feedback_survey_question_operator_intelligence_low', 'Not at all knowledgeable');
olark.configure('locale.feedback_survey_question_operator_intelligence_high', 'Extremely knowledgeable');
olark.configure('locale.feedback_survey_question_operator_speed_low', 'Not at all responsive');
olark.configure('locale.feedback_survey_question_operator_speed_high', 'Extremely responsive');
olark.configure('locale.feedback_survey_question_operator_attitude_low', 'Not at all friendly');
olark.configure('locale.feedback_survey_question_operator_attitude_high', 'Extremely friendly');
olark.configure('locale.feedback_survey_question_additional_feedback_text', 'Additional feedback.');
olark.configure('locale.feedback_survey_button_next', 'Next');
olark.configure('locale.feedback_survey_button_submitting', 'Submitting');
olark.configure('locale.feedback_survey_button_finish', 'Finish');
olark.configure('locale.feedback_survey_end_message', 'Thank you for your feedback');
olark.configure('locale.feedback_survey_submission_error_message', 'There was an error submitting your answer, please try again.');
olark.configure('locale.feedback_survey_begin_button_text', 'Rate chat');
olark.configure('locale.feedback_survey_complete_button_text', 'Done');
olark.configure('locale.feedback_survey_cancel_text', 'Cancel');
olark.configure('locale.restart_chat_online_button_text', 'Start Chatting');
olark.configure('locale.restart_chat_offline_button_text', 'Email');

/* send transcript strings */
olark.configure('locale.send_transcript_title_text', 'Send transcript');
olark.configure('locale.send_transcript_begin_button_text', 'Send transcript');
olark.configure('locale.send_transcript_complete_button_text', 'Transcript sent!');
olark.configure('locale.send_transcript_error_text', 'There was an error sending this transcript');
olark.configure('locale.send_transcript_cancel_text', 'Cancel');
olark.configure('locale.send_transcript_placeholder', 'Click here and enter your email');

With calls like olark.configure('locale.welcome_title', 'Foo'), the string provided by that call will always take highest priority.

Configure the default language
olark.configure('system.localization', 'en-US');

Enable Chat Ratings

Enable the post-chat survey on a specific page. You can also enable this on the Chat Ratings settings page.

Enable Post-chat Survey
olark.configure('features.feedback', true );

Enable Pre-chat Survey

You can enable the Pre-chat Survey feature on a specific page. This can also be done on your Text & Forms settings page.

You can read more about using the Pre-chat Survey in our help section.

Enable the Pre-chat Survey
olark.configure('features.prechat_survey', true );

Expand chatbox on load

Expand the chatbox by default when the page loads.

Note that when the chatbox is expanded, Attention Grabber images are hidden. Also, sending a message will automatically expand the chatbox in all cases by default.

Start the chat box expanded
olark.configure('box.start_expanded', true);

Hide the minimize button

Normally the chatbox shows an icon in the top right corner that, when clicked, allows the user to minimize it. This configuration option allows you to remove that button so that, once the chatbox has been expanded, the user can not manually minimize it. However, the chatbox can still be minimized and expanded with api calls.

themes

Hide the minimize button
olark.configure('system.hb_hide_minimize_button', true);

Load chatbox in DOM element

Instead of having the Olark chat window fixed to the bottom corner of your page, Olark will instead search your page for an element with the ID olark-box-container and load the chatbox there instead.

For example, you might have a <div> in your sidebar that displays the chatbox.

<div id="olark-box-container"></div>

You can find our complete instructions to embed the Olark widget on your website here

This rudimentary example shows the chatbox inside a wrapper, with a header.

<div id="wrapper">
<h1>My website</h1>
<div id="olark-box-container"></div>
</div>

It produces the example below (we are sure that you can do better!)

Screenshot of API call inline

Place the chat box inside a container
olark.configure('box.inline', true);

Page change notifications

Gives notifications about what page the visitor is on. By default, each time a visitor navigates to a new URL while on your site, this will be sent as a notification to your operator. Set to false to disable this behavior.

Report page changes to operator
olark.configure('system.give_location_to_operator', true );

Pre-chat visitor notifications

This will turn off all of the initial pre-chat notifications that give you visitor context - including location, current URL and number of previous conversations - allowing you to show just your own custom pre-chat information instead.

Disable visitor info when chat begins
olark.configure('system.disable_default_visitor_information', true);

Set operator group

Set the group before the chatbox loads. You can get the ID for each group by clicking on it from the Operator settings page.

This differs from the setOperatorGroup API call in that it can only be done before the chatbox loads. To set the operator group after the chatbox has loaded, use setOperatorGroup instead.

Lock visitor to operator group
olark.configure('system.group', string );

Single page applications

Olark uses polling to check your visitor’s status while on your site. Visitors who leave your site, or have been idle for a long time without changing page, will eventually stop sending polling requests. If you have a single page application where the visitor does not change pages, they may incorrectly be detected as being idle.

You can prevent this by setting is_single_page_application to true.

Single page applications
olark.configure('system.is_single_page_application', true );

Start chatbox hidden

Suppose you usually show the chatbox, but wish to hide it on specific pages. You can do so using the following Javascript API function. You can enable this option on your Setup page as Hide the chatbox by default.

The api.box.hide function is useful for when the chatbox has already loaded on a site and you wish to hide it again. For example, when the visitor clicks a particular button.

You would use box.start_hidden when you don’t want the chatbox to show at all when the page loads. If you used api.box.hide to hide the chatbox when the page loads, a visitor might see the chatbox appear briefly, before the API call was read.

Start the chat box hidden
olark.configure('box.start_hidden', true);

Enable Google Analytics

Use this API call to enable the Google Analytics integration on a single page.

You can also enable this in your Google Analytics Extension settings.

Enable Google Analytics
olark.configure('features.google_analytics', true );

Set Google Analytics ID

Set the Google Analytics ID for your account on a specific page.

For example, you might have separate domains using the same Olark account, but different Google Analytics IDs.

<?php

// Get the current domain
$host = $_SERVER['HTTP_HOST'];

if ($host == "example.com") {
   olark.configure('system.google_analytics_id', 'YOUR-GA-ID' );
}
elseif ($host == "test.org") {
    olark.configure('system.google_analytics_id', 'OTHER-GA-ID' );
}

?>

Check out our related help guide for this here. You can also view advanced troubleshooting help for Google Analytics + Olark here.

Set your Google Analytics ID
olark.configure('system.google_analytics_id', string );

Enable Greeter

Enable the Greeter on a specific page.

You can also enable this on the Greeter extension page.

Enable Greeter
olark.configure('features.greeter', true );

Notify operators of first-time visitors

If the Greeter function is enabled, you can use this call to enable/disable the advanced notification per page.

You can also enable this on the Greeter extension page.

Enable notification of arrival using Greeter
olark.configure('WelcomeAssist.notify_operator_of_new_visitors', true );

Set Greeter delay in seconds

Set the time after which the Greeter message will be sent to first-time visitors on your site.

You can also enable this on the Greeter extension page.

Set the Greeter delay
olark.configure('WelcomeAssist.welcome_delay_in_seconds', integer );

Set Greeter Welcome Messages

Set the welcome messages to send to the visitors when the Greeter function activates. If you have more than 1 message enabled in the call, we will choose a random one to send to the visitor when they meet the greeter criteria.

You can also enable this on the Greeter extension page.

Set the Greeter Welcome Messages
olark.configure('WelcomeAssist.welcome_messages', ['hello world', 'another message!', 'a 3rd message!']);

Switch on the Greeter

Use this call to switch the Greeter on. You can then use the calls below to control how the Greeter behaves.

You can also enable this on the Greeter extension page.

Switch on the Greeter
olark.configure('WelcomeAssist.welcome_new_visitors', true );

Add a custom prechat survey

Dynamically add questions to your prechat survey with ‘system.custom_prechat’. Pass an array of the questions you’d like to add using the format below:

olark.configure('system.custom_prechat', [
  {
    type: "textarea",
    is_required: false,
    label: 'What can we help with today?',
    placeholder_text: "I need help with..."
  }
]);

The type property refers to the type of question you would like to ask your visitors and is used in form styling and validation. Options include:

  • name,
  • email,
  • phone,
  • website,
  • textarea (good for long response questions)
  • textfield (good for short response questions).

The is_required property will mark a particular question as required or not. Required fields will appear with a * inside the input field.

The label property refers to the text above the input field. This field is only necessary to pass for questions where the type is textarea and textfield.

The placeholder_text property refers to the grey preview text inside of the input field, to help prompt visitors to fill out the form. This property is only required for textarea and textfield type questions.

These questions will be added to your existing prechat survey that you have built on the Text & Forms settings page. Keep in mind you can have a maximum of 6 questions in your prechat survey, any questions that do not fit will not appear.

This requires the pre-chat survey to be enabled first.

This setting can also be enabled on the pre-chat survey section of the Text & Forms settings page.

You can read more about using the pre-chat survey in our Help Center.

To add fields dynamically to an offline form, you can use this same format outlined above but use the system.custom_offline_form configure call.

Note: We’ll do our best to help with any questions you have. However, please keep in mind that the API is intended to be self-serve for web developers, so we’re not able to write or debug your code. If you’re experiencing issues, be sure to have your developer, designer or webmaster review code you’ve written.

Dynamically add questions to your prechat survey
olark.configure('system.custom_prechat', [
	{ 
		is_required: false, 
		label: 'What can we help with today?', 
		placeholder_text: 'I need help with ...' , 
		type: 'textarea' 
	} 
]);

Require email

Require visitors fill out their email address in the pre-chat survey before chatting. This requires the pre-chat survey to be enabled first.

This setting can also be enabled on the pre-chat survey section of the Text & Forms settings page.

You can read more about using the pre-chat survey in our Help Center.

Even if the pre-chat survey is enabled in your settings, you would need to enable the plugin using this line to use the system.ask_for_email API call:

olark.configure("features.prechat_survey", true);
Require visitors fill out their email before chatting
olark.configure('system.ask_for_email', 'hidden' );
Arguments
  • hidden
    hidden field
  • optional
    optional field
  • required
    required field

Require name

Require visitors fill out their name in the pre-chat survey before chatting. This requires the pre-chat survey to be enabled first.

This setting can also be enabled on the pre-chat survey section of the Text & Forms settings page.

You can read more about using the pre-chat survey in our Help Center.

Even if the pre-chat survey is enabled in your settings, you would need to enable the plugin using this line to use the system.ask_for_name API call:

olark.configure("features.prechat_survey", true);
Require visitors fill out their name before chatting
olark.configure('system.ask_for_name', 'hidden' );
Arguments
  • hidden
    hidden field
  • optional
    optional field
  • required
    required field

Require phone number

Require visitors fill out their phone number in the pre-chat survey before chatting. This requires the pre-chat survey to be enabled first.

This setting can also be enabled on the pre-chat survey section of the Text & Forms settings page.

You can read more about using the pre-chat survey in our Help Center.

Even if the pre-chat survey is enabled in your settings, you would need to enable the plugin using this line to use the system.ask_for_phone API call:

olark.configure("features.prechat_survey", true);
Require visitors fill out their phone before chatting
olark.configure('system.ask_for_phone', 'hidden' );
Arguments
  • hidden
    hidden field
  • optional
    optional field
  • required
    required field

Define Targeted Chat rules

Note: You can create Targeted Chat rules without any coding on the Targeted Chat settings page.

Create Targeted Chat rules that help you automate decisions about how and when to interact with visitors and operators. You can create rules to perform actions such as:

  • Initiating chat with a visitor who has been browsing for more than 30 seconds
  • Notifying an operator when a visitor lands on the page from a Google AdWords campaign
  • Highlighting important visitors in your buddy list

Be sure to check out the getDetails API call to learn how to access detailed customer information for making creative rules.

Start a conversation with a visitor after 5 pageviews

Let’s say you wanted to auto-initiate with any visitor who has visited 5 pages without talking to an operator, since maybe he is confused:

<script>
olark('api.rules.defineRule', {

    // Specify a unique ID for this rule.
    // This helps the API to keep your rules separate from each other.
    id: '1',

    // The description summarizes what this rule does
    description: "offer help to a visitor after he has browsed 5 pages and hasn't chatted yet",

    // The condition will be checked whenever there is a relevant change in the chat.
    // Call the pass() function whenever the criteria is met
    condition: function(pass) {

        // Use the Visitor API to get information the page count
        olark('api.visitor.getDetails', function(details){

            if (details.pageCountForThisVisit >= 5 && !details.isConversing) {

                // The visitor has seen more than 5 pages, and the visitor hasn't started chatting yet
                pass();
            }

        });

    },

    // The action will be executed whenever the condition passes.
    // Limit the number of times this action will trigger using the perPage, perVisit, and perVisitor options.
    action: function() {
        olark('api.chat.sendMessageToVisitor', {
            body: "hi, have any questions about our products?"
        });
    },

    // Restrict this action to execute only once per visit
    perVisit: true

});
</script>

Start a conversation on specific pages

Maybe you would like to hide the chatbox on certain pages, but only if the visitor is not already chatting:

<script>
olark('api.rules.defineRule', {

    // Specify a unique ID for this rule.
    // This helps the API to keep your rules separate from each other.
    id: '2',

    // The description summarizes what this rule does
    description: "hide the chatbox when the visitor is not chatting and is viewing an unimportant page",

    // The condition will be checked whenever there is a relevant change in the chat.
    // Call the pass() function whenever the criteria is met
    condition: function(pass) {

        // Check if the visitor is already in conversation
        // ...and whether they're on a specific page
        olark('api.visitor.getDetails', function(details){

            // Determine whether this page is important
            // The URL can be whatever you like
            var isImportantPage = (details.currentPage.url.indexOf('/important-page') >= 0);

            if (!details.isConversing && !isImportantPage) {

                // Visitor is not chatting yet
                // and they are viewing an unimportant page
                pass();

            }

        });

    },

    // The action will be executed whenever the condition passes.
    // Limit the number of times this action will trigger using the perPage, perVisit, and perVisitor options.
    action: function() {

        // Hide the chatbox
        olark('api.box.hide');

    },

    // Restrict this action to execute only once per page
    perPage: true

});
</script>
Create Targeted Chat rules
olark('api.rules.defineRule', { options });
Arguments
  • options.action
    function that performs the action, e.g. notifying the operator (see examples below)
  • options.condition
    function that evaluates a condition and calls pass when true (see examples below)
  • options.description
    human-readable description of what this rule does, e.g. 'notifies the operator about important visitors'
  • options.id
    unique identifier for this rule, e.g. _important_visitor_rule_1_
  • options.perpage
    make this true if the action is only supposed to trigger once per page. OR::
  • options.pervisit
    make this true if the action is only supposed to trigger once per visit OR:
  • options.pervisitor
    make this true if the action is only supposed to trigger once per visitor

Get visitor details

Gets the email address, full name, geolocation, and other details for this visitor. The value will be returned to the specified returnCallback.

The name, email and phone number fields are the last-known visitor information, either from your pre-chat survey, a completed offline message form, or previously updated via the API.

Geolocation information is provided to the best of our knowledge, based on the visitor’s IP.

Note: As part of our effort to remove personally identifiable information from our API, this call no longer provides access to the visitor’s IP address. Please visit olark.com/help/ipaddresses to learn more.

Notify operators about a certain visitor

Let’s say you wanted to know when a particular customer (e.g. Olark Joe) needed your assistance:

<script>
    olark('api.visitor.getDetails', function(details){

        // Check for an email address
        if (details.emailAddress == "joe@olark.com") {

            olark('api.chat.sendNotificationToOperator', {
                body: "Olark Joe in the house!"
            });

        }
    });
</script>

Target customers in Costa Rica

Let’s say you are targeting customers in San José, the capital of Costa Rica (not San Jose in California):

<script>
olark('api.visitor.getDetails', function(details){

    // Check that both conditions are true
    if (details.city == "San José" && details.region != "California") {

        olark('api.chat.sendNotificationToOperator', {
            body: "this customer might be in San Jose, Costa Rica"
        })

    }

});
</script>

Target customers in Japan

Suppose you are targeting customers in Japan. You can either use the country name or the country code:

<script>
olark('api.visitor.getDetails', function(details){

    if (details.country == "Japan" || details.countryCode == "JP") {

        olark('api.chat.sendNotificationToOperator', {
            body: "this customer might be in Japan"
        });

    }

});
</script>
Read the visitor informaton
olark('api.visitor.getDetails', callback);
Response
  • details.browser
    the browser that this visitor is using (e.g. 'Chrome 12.1')
  • details.city
    approximate city location
  • details.conversationbeginpage
    the URL from which the visitor began their conversation"
  • details.conversationcount
    total number of times this visitor has chatted with an operator"
  • details.country
    approximate country
  • details.countrycode
    approximate country (in ISO-standard format, e.g. UK, DE, JP, etc)
  • details.currentpage
    the current page the visitor is on (has a title and URL)
  • details.customfields.yourfieldnamegoeshere
    you can retrieve any custom fields that you set with api.visitor.updateCustomFields
  • details.emailaddress
    visitor's email address
  • details.fullname
    visitor's full name
  • details.ip
    This will return "not available" in an effort to remove PII from our API.
  • details.isconversing
    will be true if the visitor is having a conversation right now"
  • details.messagecountacrossallvisits
    number of messages sent and received for this visitor all-time on your site"
  • details.messagecountforthisvisit
    number of messages sent and received during this conversation"
  • details.operatingsystem
    the operating system that this visitor is using (e.g. Windows, Mac, or Linux)
  • details.organization
    organization that this visitor might be affiliated with
  • details.pagecountacrossallvisits
    total number of pages that this visitor has viewed all-time on your site
  • details.pagecountforthisvisit
    number of pages that this visitor has viewed during this visit
  • details.phonenumber
    visitor's phone number
  • details.recentpagehistory
    a list of the last 10 pages seen by the visitor (each page has a title and URL)
  • details.referredbycampaignever
    will be true if the visitor came to your site from an email or blogging campaign at some point
  • details.referredbycampaignthisvisit
    will be true if the visitor came to your site from an email or blogging campaign this visit
  • details.referredbypaidadvertisingever
    will be true if the visitor came to your site from a paid advertisement at some point
  • details.referredbypaidadvertisingthisvisit
    will be true if the visitor came to your site from a paid advertisement for this visit
  • details.referrer
    the URL that referred this visitor to your website (e.g. a Google search, advertisement, blog post, etc)
  • details.region
    approximate state or province
  • details.searchtextforpreviousvisits
    search text that was typed in Google, Yahoo, or Bing to get to your site in past visits
  • details.searchtextforthisvisit
    search text that was typed in Google, Yahoo, or Bing to get to your site
  • details.secondssincelastmessage
    seconds since either the visitor or operator sent a message"
  • details.secondssincelastmessagetooperator
    seconds since the visitor sent a message"
  • details.secondssincelastmessagetovisitor
    seconds since the operator sent a message"
  • details.secondssincelastnotificationtooperator
    seconds since the operator last received a notification"
  • details.secondsspentacrossallvisits
    total number of seconds that this visitor has spent on your site over all their visits
  • details.secondsspentforthisvisit
    number of seconds that this visitor has spent on your site
  • details.visitcount
    total number of times this visitor has visited your site

Update CRM custom fields

If you have custom data that you want to keep track of for a visitor, such as an internal customer ID or some internal data, you can give it to Olark using this API.

Note: Custom fields are not sent automatically to CRM integrations. Custom fields will, however, be sent with Webhooks by default. Once set up, Custom fields are sent to the CRM only, they do not appear in the chat console. For full information on creating custom fields, check out our blog post here!

Adding a customer ID

For example, let’s say you have a customer tracking ID that you use for your internal reporting. You can give this to Olark:

<script>
olark('api.visitor.updateCustomFields', {

    // Replace with your own data
    internalCustomerId: '2194832109'

});
</script>
Set custom fields for the visitor
olark('api.visitor.updateCustomFields', {
	internalCustomerId: string
});
Arguments
  • dictionaryofcustomfields
    a dictionary mapping custom field name=>value

Update visitor email

Keep track of an email address for this visitor, to link it with your CRM cases and display in the visitor list.

Screenshot of API call update email

Update the visitor’s email address

You can grab information from your registered users and send it to Olark.

<script>
olark('api.visitor.updateEmailAddress', {
    emailAddress: 'johndoe@olark.com'
});
</script>
Set the visitor's email
olark('api.visitor.updateEmailAddress', {
	emailAddress: string
});
Arguments
  • options.emailaddress
    the email address to remember

Update visitor name

Keep track of a full name for this visitor, to link it with your CRM cases and display in the buddy list.

Screenshot of API call update name

Update the visitor’s name

You can grab information from your registered users and send it to Olark.

<script>
olark('api.visitor.updateFullName', {
    fullName: 'John Doe'
});
</script>

For example, if you were using PHP and pulled the visitor’s name from your own database, you might write:

<script>
olark('api.visitor.updateFullName', {
    fullName: '<?php echo $user_name ?>'
});
</script>
Set the visitor's name
olark('api.visitor.updateFullName', {
	fullName: string
});
Arguments
  • options.fullname
    the name to remember

Update visitor nickname

Important Note:
updateVisitorNickname is best used to display visitor information other than name and email in the buddy list. To display a name and/or email in the buddy list use api.visitor.updateFullName and api.visitor.updateEmailAddress respectively.

Add information to the visitor’s nickname in the operator’s buddy list. You can only set a ‘snippet’ of the nickname, since other extensions may be trying to update the nickname at the same time.

Highlight AdWords referrals in your visitors list

Let’s say you want to highlight valuable visitors in your buddy list. For example you have already paid money for a visitor to click on your AdWords campaign, or when they search for the term “buying widgets”:

<script>
olark('api.visitor.getDetails', function(details){

    if (details.referredByPaidAdvertisingThisVisit) {

        olark('api.chat.updateVisitorNickname',{
            snippet: "AdWords Referral"
        })

    } else if (details.searchTextForThisVisit == "buying widgets") {

        olark('api.chat.updateVisitorNickname', {
            snippet: "wants to buy a widget"
        })

    }

});
</script>
Set the visitor's nickname
olark('api.chat.updateVisitorNickname', {
	snippet: '',
	hidesDefault: true
});
Arguments
  • options.hidesdefault
    (optional) set this to true if you want to hide the default nickname that Olark sets
  • options.snippet
    the snippet of text to show as part of the nickname

Update visitor phone

Keep track of a phone number for this visitor, to link it with your transcripts and display in the visitor list.

Update a visitor’s phone number

You can grab information from your registered users and send it to Olark.

<script>
    olark('api.visitor.updatePhoneNumber', {
        phoneNumber: '(123) 456-7890'
    });
</script>
Set the visitor's phone number
olark('api.visitor.updatePhoneNumber', {
	phoneNumber: string
});
Arguments
  • options.phonenumber
    the phone number to remember

Update visitor status

Add information to the visitor’s status in the operator’s buddy list. You can only set a ‘snippet’ of the status, since other extensions may be trying to update the status at the same time.

Display number of items in a shopping cart

To show custom information, like the number of items somebody has in their shopping cart:

<script>
    olark('api.chat.updateVisitorStatus', {
        snippet: 'has 10 items in cart'
    });
</script>

Screenshot of API call visitor status

Do you have multiple pieces of information? Use an array for the snippet:

<script>
    olark('api.chat.updateVisitorStatus', {
        snippet: ['has 10 items in cart', 'value of items is $38']
    });
</script>

The Olark chat console automatically tries to detect email addresses, storing them as the visitor’s information. In this example, the first item in the snippet array is the equivalent of using the `api.visitor.updateEmailAddress' API call:

// Sets email as test@example.com
// and "Some text" appears as Advanced Info
olark('api.chat.updateVisitorStatus', {
    snippet: ["test@example.com", "Some text"]
});
Set the visitor's status
olark('api.chat.updateVisitorStatus', {
	snippet: ''
});
Arguments
  • options.snippet
    the snippet of text to show as part of the status