Developers

Widget JavaScript API

Control the chat from your website: open it from a button, pass the signed-in user’s contacts, send events to analytics.

The SanaChat object

After the widget loads, window.SanaChat is available. To run code right after loading use the ready event or window.sanaOnReady.

Methods

  • SanaChat.open() / close() / toggle() — open, close, toggle the window;
  • SanaChat.isOpen(), isOnline() — is the window open, are agents online;
  • SanaChat.setContact({name, email, phone}) — pass the signed-in user: the agent sees who is writing;
  • SanaChat.sendMessage('text') — send a message as the visitor (for example from a “Get a price” button);
  • SanaChat.callback() — show the call-back form;
  • SanaChat.on(event, fn) / off(event, fn) — subscribe to events.

Events

ready, open, close, message (data: id, sender — visitor, operator or bot, text). The same events fire as DOM events sana:ready, sana:message and so on.

Pass the user

<script>
window.sanaOnReady = function () {
  SanaChat.setContact({ name: 'Anna Smith', email: 'anna@example.com', phone: '+77011234567' });
};
</script>
<script src="//sana-chat.com/w/SITE_KEY" async></script>

Your own “Ask a question” button

<button onclick="SanaChat.open()">Ask a question</button>
<button onclick="SanaChat.sendMessage('I would like a price for the Business plan')">Get a price</button>

Events to Google Analytics / Yandex Metrica

SanaChat.on('message', function (m) {
  if (m.sender === 'visitor') {
    window.dataLayer = window.dataLayer || [];
    dataLayer.push({ event: 'chat_message' });
    if (window.ym) ym(12345678, 'reachGoal', 'chat_message');
  }
});

Switching off

The platform owner can temporarily switch off passing contacts (setContact); the other methods always work.

Questions and answers

Do I need user consent to pass their data?

Pass data only for users who signed in on your site and accepted your privacy policy.

Can I open the chat with my own button?

Yes, call SanaChat.open() from your button.

Does the JS API work on the chat page?

Yes, SanaChat is available wherever the widget loads.

Still have questions?

Write to us in the chat — we reply within minutes and help you set everything up. Or leave a message on the contacts page.

Related