Resources

Javascript API

Our documentation to help you customize Olark to fit your website
API Functions
Attention GrabberEnable Attention Grabberfeatures.attention_grabberOnline Attention Grabber imageCalloutBubble.bubble_image_urlOffline Attention Grabber imageCalloutBubble.offline_bubble_image_urlAttention Grabber image widthCalloutBubble.bubble_widthAttention Grabber image heightCalloutBubble.bubble_heightAttention Grabber animationCalloutBubble.slideChat box behaviorShow the chatboxapi.box.showHide the chatboxapi.box.hideExpand the chatboxapi.box.expandMinimize the chatboxapi.box.shrinkOn chatbox showapi.box.onShowOn chatbox hideapi.box.onHideOn chatbox expandapi.box.onExpandOn chatbox minimizeapi.box.onShrinkChat conversationOn chatbox loadapi.chat.onReadyChange operator groupapi.chat.setOperatorGroupOn operators availableapi.chat.onOperatorsAvailableOn operators unavailableapi.chat.onOperatorsAwayOn conversation startapi.chat.onBeginConversationOn message to operatorapi.chat.onMessageToOperatorOn message to visitorapi.chat.onMessageToVisitorOn operator commandapi.chat.onCommandFromOperatorSend message to visitorapi.chat.sendMessageToVisitorSend operator notificationapi.chat.sendNotificationToOperatorSend visitor notificationapi.chat.sendNotificationToVisitorOffline message sentapi.chat.onOfflineMessageToOperatorConfigure the chat boxEnable Chat Ratingsfeatures.feedbackEnable Cobrowsingfeatures.cobrowsingEnable Pre-chat Surveyfeatures.prechat_surveySet chatbox positionbox.corner_positionAllowed domainssystem.allowed_domainsExpand chatbox on loadbox.start_expandedStart chatbox hiddenbox.start_hiddenLoad chatbox in DOM elementbox.inlinePage change notificationssystem.give_location_to_operatorPre-chat visitor notificationssystem.disable_default_visitor_informationSet operator groupsystem.groupSingle page applicationssystem.is_single_page_applicationPrevent non-local URL wrappingsystem.chat_does_not_follow_external_linksGoogle AnalyticsEnable Google Analyticsfeatures.google_analyticsSet Google Analytics IDsystem.google_analytics_idGreeterEnable Greeterfeatures.greeterSet Greeter delay in secondsWelcomeAssist.welcome_delay_in_secondsSet Greeter Welcome MessagesWelcomeAssist.welcome_messagesNotify operators of first-time visitorsWelcomeAssist.notify_operator_of_new_visitorsPre-chat surveyRequire namesystem.ask_for_nameRequire emailsystem.ask_for_emailRequire phone numbersystem.ask_for_phoneTargeted ChatDefine Targeted Chat rulesapi.rules.defineRuleVisitor informationGet visitor detailsapi.visitor.getDetailsUpdate visitor nicknameapi.chat.updateVisitorNicknameUpdate visitor statusapi.chat.updateVisitorStatusUpdate visitor nameapi.visitor.updateFullNameUpdate visitor emailapi.visitor.updateEmailAddressUpdate visitor phoneapi.visitor.updatePhoneNumberUpdate CRM custom fieldsapi.visitor.updateCustomFields

Getting started with the API

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.

  1. Make sure you have the latest Olark embed code.
  2. Use the !develop command from the operator-side of the chat to reveal visitor-side developer tools.
  3. For olark.configure API calls, place them in your existing Olark before olark.identify as shown below:

    /* 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.

Support

If you have a problem with an API call, such as it not returning the correct value or not performing the intended action, email support@olark.com with a link to a page where we can test the functionality and information about the steps that you've taken to debug so far.

Testing and Debugging

The API is intended to be self-serve. Although we can't debug or write JavaScript for you, there are some helpful ways to test your own code during development:

Learning JavaScript

If you're new to JavaScript entirely, you might want to start with one of these courses:

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.

<script>
// 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 );

}
</script>
Enable the Attention Grabber
olark.configure('features.attention_grabber', false );

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:

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

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:

<script>
olark.configure('CalloutBubble.offline_bubble_image_url', 'path/to/file' );
</script>
Offline Attention Grabber image
olark.configure('CalloutBubble.offline_bubble_image_url', 'path/to/file' );

Attention Grabber image width

Set the Attention Grabber image width in pixels.

For example:

<script>
olark.configure('CalloutBubble.bubble_width', 100 );
</script>

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 );

Attention Grabber image height

Set the Attention Grabber image height in pixels.

For example:

<script>
olark.configure('CalloutBubble.bubble_height', 25 );
</script>

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 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.

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

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

}
</script>

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

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', false );

Show the chatbox

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

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 chat box 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 chat box
if (errorOnPage) {
    olark('api.box.show');
}
</script>
Unhide the chat box
olark('api.box.show');

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.

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');

Expand the chatbox

Expands the chatbox to its fully expanded height. It will also show the chat box 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 chat box.

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');

Minimize the chatbox

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

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 show

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

Update visitor status when chat box visible

If you have chosen to have your chat box 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
});

On chatbox hide

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

Notify an operator when a visitor closes the chat box

You can notify your operator that the visitor has closed the box 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 expand

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

Watch for visitors clicking the chat box

A visitor to your site might expand the chat box, 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 minimize

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

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.onConversationBegin', 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 load

Use this API call to detect when the Olark chat box 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.

Here is a guide to resizing the chatbox once Olark has loaded, it is a great example of the use of onReady.

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

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 Advanced settings.

<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

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 chat box 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>

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 chat box 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>

Trigger for when operators are away
olark('api.chat.onOperatorsAway', 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.body.message.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.onMessageToOpeator', 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

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 note 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 !note command
    if (event.command.name == 'note') {

        // 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.name
    the name of the command, e.g. 'track' (required)
  • event.command.body
    the contents of the message, e.g. 'this is a lead' (optional)

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', {
	// Your callback function
});
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.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

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="http://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

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', false );

Enable Cobrowsing

You can enable the Cobrowsing feature on a per page basis. This can also be done on your Cobrowsing settings page.

For more documentation on how to use the cobrowsing feature, check out the cobrowsing article in our help section.

Programatically enable the Cobrowsing feature
olark.configure('features.cobrowsing', true);

Enable Pre-chat Survey

You can enable the Pre-chat Survey feature on a specific page. This can also be done on your Behavior and Text 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', false );

Set chatbox position

You can use this Javascript API call to change the loading position of the chat box to different corners on individual pages of your website.

Not all themes can be placed in all four corners. Check out the Appearance settings to see which options are available which themes.

When would I use this?

It's preferable to change this setting in your Olark account's Appearance settings.

However, if you have a particular page where you need to change the position of the chat box - for example if it would obscure another element - then it might make sense to alter the position on a page-by-page basis.

Take the time to consider the consequences of moving the chat box per-page. If a visitor starts a conversation with you while the chat box is in one corner, they may be surprised to see the chat box load in another corner on a different page.

Set the chat box location
olark.configure('box.corner_position', option );
Arguments
  • TL
    Top left
  • TR
    Top right
  • BR
    Bottom right
  • BL
    Bottom right

Allowed domains

Set which domains the chatbox will be display 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 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.

<script>
    olark.configure('system.allowed_domains', '*.yourdomain.com,*.yourotherdomain.com');
</script>

You can also enable this setting on our Advanced Settings page.

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

Expand chatbox on load

Expand the chat box by default when the page loads. This setting can also be enabled in the Advanced Settings.

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

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

Start chatbox hidden

Suppose you usually show the chat box, but wish to hide it on specific pages. You can do so using the following Javascript API function. You can enable this option in your Advanced Settings as Invisible Olark.

The api.box.hide function is useful for when the chat box 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 chat box to show at all when the page loads. If you used api.box.hide to hide the chat box when the page loads, a visitor might see the chat box appear briefly, before the API call was read.

Start the chat box hidden
olark.configure('box.start_hidden', 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 chat box there instead.

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

<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 chat box 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!)

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 chat box 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 chat box loads. To set the operator group after the chat box 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', false );

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', false);

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', false );

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!']);

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 );

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 Behavior and Text 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
  • required
    required field
  • optional
    optional field
  • hidden
    hidden field

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 Behavior and Text 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
  • required
    required field
  • optional
    optional field
  • hidden
    hidden 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 Behavior and Text 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
  • required
    required field
  • optional
    optional field
  • hidden
    hidden 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 chat box
        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.id
    unique identifier for this rule, e.g. _important_visitor_rule_1_
  • options.description
    human-readable description of what this rule does, e.g. 'notifies the operator about important visitors'
  • options.condition
    function that evaluates a condition and calls pass when true (see examples below)
  • options.action
    function that performs the action, e.g. notifying the operator (see examples below)
  • 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.

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>

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>

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.emailAddress
    visitor's email address
  • details.fullName
    visitor's full name
  • details.phoneNumber
    visitor's phone number
  • details.city
    approximate city location
  • details.region
    approximate state or province
  • details.country
    approximate country
  • details.countryCode
    approximate country (in ISO-standard format, e.g. UK, DE, JP, etc)
  • details.organization
    organization that this visitor might be affiliated with
  • details.visitCount
    total number of times this visitor has visited your site
  • details.pageCountForThisVisit
    number of pages that this visitor has viewed during this visit
  • details.pageCountAcrossAllVisits
    total number of pages that this visitor has viewed all-time on your site
  • details.secondsSpentForThisVisit
    number of seconds that this visitor has spent on your site
  • details.secondsSpentAcrossAllVisits
    total number of seconds that this visitor has spent on your site over all their visits
  • details.currentPage
    the current page the visitor is on (has a title and URL)
  • details.recentPageHistory
    a list of the last 10 pages seen by the visitor (each page has a title and URL)
  • details.conversationCount
    total number of times this visitor has chatted with an operator"
  • details.isConversing
    will be true if the visitor is having a conversation right now"
  • details.messageCountForThisVisit
    number of messages sent and received during this conversation"
  • details.messageCountAcrossAllVisits
    number of messages sent and received for this visitor all-time on 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.conversationBeginPage
    the URL from which the visitor began their conversation"
  • details.referrer
    the URL that referred this visitor to your website (e.g. a Google search, advertisement, blog post, etc)
  • details.referredByPaidAdvertisingThisVisit
    will be true if the visitor came to your site from a paid advertisement for this visit
  • details.referredByPaidAdvertisingEver
    will be true if the visitor came to your site from a paid advertisement at some point
  • details.referredByCampaignThisVisit
    will be true if the visitor came to your site from an email or blogging campaign this visit
  • details.referredByCampaignEver
    will be true if the visitor came to your site from an email or blogging campaign at some point
  • details.searchTextForThisVisit
    search text that was typed in Google, Yahoo, or Bing to get to your site
  • details.searchTextForPreviousVisits
    search text that was typed in Google, Yahoo, or Bing to get to your site in past visits
  • details.browser
    the browser that this visitor is using (e.g. 'Chrome 12.1')
  • details.operatingSystem
    the operating system that this visitor is using (e.g. Windows, Mac, or Linux)
  • details.ip
    the raw IP address for this visitor (e.g. '123.234.234.64')
  • details.customFields.yourFieldNameGoesHere
    you can retrieve any custom fields that you set with api.visitor.updateCustomFields

Update visitor nickname

Deprecation notice27th January 2015
updateVisitorNickname is being deprecated. While the API call will continue to function as before, we'll no longer be supporting it, favoring other API calls such as updateFullName and updateVisitorStatus.
If you have any questions, chat or email us for more information.

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.

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

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>

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>
Set the visitor's status
olark('api.chat.updateVisitorStatus', {
	snippet: ''
});
Arguments
  • options.snippet
    the snippet of text to show as part of the status

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.

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 $user-name ?>'
});
</script>
Set the visitor's name
olark('api.visitor.updateFullName', {
	fullName: string
});
Arguments
  • options.fullName
    the name to remember

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.

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 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 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. Presently, this is something you would need to email support@olark.com to help set up. Custom fields will however be sent with Webhooks by default.

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
Your customers are already on your site. Talk to them.