Gorgias logo
Gorgias logo

All articles

HTML snippets for chat customizationUpdated 14 minutes ago

Who can use this feature?

You need admin permissions in Gorgias and your ecommerce store to customize the chat
Available for Shopify and BigCommerce stores connected to Gorgias

The Gorgias chat widget exposes a JavaScript API and several window-level variables that let you control widget behavior, appearance, and content beyond what's configurable in the settings. This article covers every supported customization technique in one place, organized by what you're trying to accomplish. For an explanation of how the customization layer works and where to place your code, see Customize the chat widget with HTML and JavaScript.

Note: These customizations require working knowledge of HTML and JavaScript. They go beyond the built-in features of the chat widget, and Gorgias support cannot troubleshoot custom code. Have a developer implement and maintain any scripts you add to your site.

Example code snippets

We've compiled some common customization snippets below. Select an option from the list below to jump directly to it, or scroll through this article to browse each snippet.



Using URL parameters

Some behaviors can be triggered through URL query parameters, without writing any JavaScript. These work by appending a parameter to any page URL on your site.

Open the chat automatically on page load by adding gs_open_chat to the URL:

1https://www.my-store.com?gs_open_chat
2

Pre-fill the chat input field with a message by adding gs_chat_message to the URL. The message text must be URL-encoded — spaces become %20, for example:

1https://www.my-store.com?gs_chat_message=I%20have%20a%20question%20about%20my%20order
2

You can use an online tool such as urlencoder.org to encode your message string before adding it to the URL.

Navigate the chat to a specific view on load by adding gs_chat_page to the URL. Valid values are:

  • conversation — navigates to the live chat view if agents are online, or the offline contact form if not
  • chat — always navigates to the live chat view, regardless of online status
  • homepage — navigates to the AI Agent automation features self-service home screen (falls back to the live chat view if automation features aren't enabled)
1https://www.my-store.com?gs_chat_page=conversation
2

Combine multiple parameters by separating them with &. For example, to open the chat automatically, navigate to the conversation view, and pre-fill a message all at once:

1https://www.my-store.com?gs_open_chat&gs_chat_page=conversation&gs_chat_message=Hello
2

Setting window variables before the widget loads

Two customizations must be set as window variables before the widget initializes — they cannot use the GorgiasChat.init() wrapper. Unlike all other scripts in this article, these must be placed before the Gorgias installation snippet, in your page's <head> or at the very top of <body>.

Disable auto-open for returning customers. By default, the chat window opens automatically for returning visitors whose last visit was less than four days ago (except on mobile). To disable this:

1<script>
2 window.GORGIASCHAT_DISABLE_AUTO_OPEN = true
3</script>
4

Disable automatic font color adjustment. The chat automatically adjusts font and icon color based on your configured background color to maintain readability and accessibility contrast ratios. To prevent this and keep your font color exactly as configured:

1<script>
2 window.GORGIASCHAT_DISABLE_CONTRAST_COLOR = true
3</script>
4

Using the GorgiasChat API

All other customizations use the GorgiasChat JavaScript object, which is available on the page after the widget initializes. Because the widget loads asynchronously, you must always wait for it before calling any GorgiasChat methods. Use this initialization wrapper for every script in this article:

1var initGorgiasChatPromise = (window.GorgiasChat)
2 ? window.GorgiasChat.init()
3 : new Promise(function (resolve) {
4 window.addEventListener('gorgias-widget-loaded', function () { resolve(); })
5 });
6
7initGorgiasChatPromise.then(function () {
8 // Your custom code goes here
9});
10

Place each <script> tag after the Gorgias installation snippet, before the closing </body> tag.


Controlling widget visibility

Use these scripts to control where and when the chat appears on your site.

Hide the chat on specific pages

Replace the URL strings in pagesToHide with the full URLs of the pages where you want the chat hidden:

1var pagesToHide = [
2 'https://www.my-store.com/checkout',
3 'https://www.my-store.com/account',
4]
5
6var initGorgiasChatPromise = (window.GorgiasChat)
7 ? window.GorgiasChat.init()
8 : new Promise(function (resolve) {
9 window.addEventListener('gorgias-widget-loaded', function () { resolve(); })
10 });
11
12initGorgiasChatPromise.then(function () {
13 if (pagesToHide.includes(window.location.href)) {
14 GorgiasChat.hideChat(true);
15 }
16})
17

Display the chat after a time delay

To prevent the widget from appearing immediately on page load — for example, to let visitors orient themselves before the chat appears — hide it on load and reveal it after a set number of seconds. Change the value passed to sleep() to the number of seconds you want to wait:

1var initGorgiasChatPromise = (window.GorgiasChat)
2 ? window.GorgiasChat.init()
3 : new Promise(function (resolve) {
4 window.addEventListener('gorgias-widget-loaded', function () { resolve(); })
5 });
6
7initGorgiasChatPromise.then(async function () {
8 var chatElem = document.getElementById('gorgias-chat-container');
9 chatElem.style.display = 'none';
10
11 function sleep(seconds) {
12 return new Promise(resolve => setTimeout(resolve, seconds * 1000));
13 }
14
15 await sleep(5); // Change this to the number of seconds to wait before showing the chat
16 chatElem.style.display = '';
17})
18

Hide the chat based on the visitor's country

This script uses the ipstack geolocation API to check the visitor's country code. If the country is not on the allowlist, the chat is hidden. Replace YOUR_API_KEY with your ipstack API key, and update the countryCodeWhiteList array with the country codes where you want the chat to appear.

ipstack free accounts are limited to 5,000 requests per month. If your traffic exceeds that, you will need a paid ipstack plan.
1<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
2<script>
3var ipstackAPIKey = 'YOUR_API_KEY'
4var countryCodeWhiteList = ['US', 'MX']
5var useHttps = true // Set to false if you are on a free ipstack account
6
7var initGorgiasChatPromise = (window.GorgiasChat)
8 ? window.GorgiasChat.init()
9 : new Promise(function (resolve) {
10 window.addEventListener('gorgias-widget-loaded', function () { resolve(); })
11 });
12
13function removeGorgiasChat(countryCode) {
14 initGorgiasChatPromise.then(function () {
15 var container = document.querySelector('#gorgias-chat-container');
16 if (container && !countryCodeWhiteList.includes(countryCode)) {
17 container.remove()
18 }
19 })
20}
21
22var countryCode = window.localStorage.getItem('countryCode')
23if (!countryCode) {
24 var protocol = useHttps ? 'https' : 'http'
25 $.ajax({
26 url: protocol + '://api.ipstack.com/check?access_key=' + ipstackAPIKey + '&fields=country_code',
27 dataType: 'jsonp',
28 success: function (json) {
29 countryCode = (json && json.country_code) ? json.country_code : 'unknown'
30 window.localStorage.setItem('countryCode', countryCode)
31 removeGorgiasChat(countryCode)
32 },
33 error: function () {
34 window.localStorage.setItem('countryCode', 'unknown')
35 removeGorgiasChat('unknown')
36 }
37 })
38} else {
39 removeGorgiasChat(countryCode)
40}
41</script>
42

Control the widget programmatically

To add a link anywhere on your page that opens the chat when clicked:

1<a onclick="GorgiasChat.open();">Start a chat with our team</a>
2

To add a link that closes the chat:

1<a onclick="GorgiasChat.close();">Close the chat</a>
2

Check whether the chat is open

Use GorgiasChat.isOpen() inside the init wrapper to check whether the chat window is currently open. It returns true or false:

1initGorgiasChatPromise.then(function () {
2 GorgiasChat.isOpen()
3})
4

Pre-fill the message input field

To pre-fill the chat input field with a string when the page loads:

1initGorgiasChatPromise.then(function () {
2 GorgiasChat.setCurrentInput('Hello, I have a question about my order.')
3})
4

Send a message programmatically

To send a message on behalf of the visitor as soon as the widget is ready:

1initGorgiasChatPromise.then(function () {
2 GorgiasChat.sendMessage('I have a question about my order.')
3})
4

If the chat window is closed when this runs, the message waits until the visitor opens it. If the widget is never opened, the message is never sent. To guarantee the message sends, open the chat first:

1initGorgiasChatPromise.then(function () {
2 GorgiasChat.open()
3 GorgiasChat.sendMessage('I have a question about my order.')
4})
5

Use GorgiasChat.setPage() to navigate the widget to a specific view. Valid values are 'conversation' (navigates to the live chat view if agents are online, or the offline contact form if not), 'chat' (always navigates to the live chat view), and 'homepage' (the AI Agent automation features self-service home screen, if these automation features are enabled — falls back to the live chat view if not):

1initGorgiasChatPromise.then(function () {
2 GorgiasChat.setPage('conversation')
3 // or
4 GorgiasChat.setPage('homepage')
5})
6

Subscribing to chat events

Use GorgiasChat.on() to run code when specific chat events occur. Replace EVENT_NAME with one of the supported event names listed below:

1initGorgiasChatPromise.then(function () {
2 GorgiasChat.on('EVENT_NAME', function (data) {
3 // your code here
4 })
5})
6

To stop listening to an event, use GorgiasChat.off('EVENT_NAME', listener) — you must pass the same function reference that was registered with on().

Supported events:

  • ready — fires when the chat has rendered on the page
  • destroy — fires when the chat is unmounted
  • widget:opened — fires when the chat window opens
  • widget:closed — fires when the chat window closes
  • message:received — fires when a message is received; data contains the message attributes
  • message:sent — fires when a message is sent; data contains the message attributes
  • message — fires when any message is sent or received; data contains the message attributes
  • unreadCount — fires when the unread message count changes; data contains the new count
  • connected — fires when a connection to the chat server is established
  • disconnected — fires when the connection to the chat server is lost
  • typing:start — fires when an agent begins typing
  • typing:stop — fires when an agent stops typing
  • campaign:opened — fires when a chat campaign opens
  • campaign:closed — fires when a chat campaign closes

Checking business hours

Check whether the current time is within business hours

GorgiasChat.isBusinessHours() returns true if the current time falls within your configured business hours. This value is only reliable after the chat has initialized:

1initGorgiasChatPromise.then(function () {
2 GorgiasChat.isBusinessHours() // returns true or false
3})
4

Set custom business hours via script

You can override the business hours configured in your helpdesk settings using setCustomBusinessHours(). This is useful if your business hours vary dynamically. Timezone values must match entries from the IANA tz database. Days are numbered 1 (Monday) through 7 (Sunday):

1initGorgiasChatPromise.then(function () {
2 GorgiasChat.setCustomBusinessHours({
3 timezone: 'Australia/Sydney',
4 businessHours: [
5 { days: [1, 2, 3], fromTime: '08:15', toTime: '17:50' },
6 { days: [4, 5], fromTime: '08:15', toTime: '12:00' }
7 ]
8 })
9})
10

If Hide chat outside of business hours is enabled in your settings, the widget will appear or disappear automatically based on these custom hours.


Capturing customer data

Associate an email address with a chat session

Use captureUserEmail() to link a visitor's email to their current chat session. This is useful when you have the customer's email from a login session and want it associated with incoming chat conversations automatically. Pass a valid, real email address — passing [email protected] or similar placeholder values will throw an error:

1initGorgiasChatPromise.then(function () {
2 GorgiasChat.captureUserEmail('[email protected]')
3})
4

Capture the Shopify cart (Shopify stores only)

Link the visitor's current Shopify cart to their chat session so agents can see cart details in the ticket sidebar. This fetches the cart from Shopify's API and passes it to the chat:

1async function getCart(url = '/cart.json') {
2 const response = await fetch(url, { method: 'GET' });
3 return response.json();
4}
5
6var initGorgiasChatPromise = (window.GorgiasChat)
7 ? window.GorgiasChat.init()
8 : new Promise(function (resolve) {
9 window.addEventListener('gorgias-widget-loaded', function () { resolve(); })
10 });
11
12initGorgiasChatPromise.then(function () {
13 getCart().then(function (cart) {
14 GorgiasChat.captureShopifyCart(cart)
15 })
16})
17

Disabling analytics

Disable Segment tracking

Gorgias uses Segment for analytics. To disable it — for example, to comply with privacy requirements — call disableSegment(). Place this at the top of your customization scripts so it runs before any other API call triggers a tracking event:

1initGorgiasChatPromise.then(function () {
2 GorgiasChat.disableSegment()
3})
4

Customizing widget appearance

The chat widget renders its button, window, and campaigns in separate iframes. Injecting custom CSS requires waiting for the iframe's internal stylesheet to finish loading, which is why these scripts use a polling interval (setInterval) to detect when the styles are ready before appending custom rules.

CSS class names inside the chat iframes (such as those generated by Emotion) are not stable — they can change between widget versions. Style by element ID or semantic selectors where possible. Any CSS injected this way may break when the widget is updated.

Add custom CSS to the chat button

Replace the content of buttonStyle.textContent with your own CSS rules:

1var initGorgiasChatPromise = (window.GorgiasChat)
2 ? window.GorgiasChat.init()
3 : new Promise(function (resolve) {
4 window.addEventListener('gorgias-widget-loaded', function () { resolve(); })
5 });
6
7initGorgiasChatPromise.then(function () {
8 var timer = setInterval(function () {
9 var chatButtonHead = document.querySelector('#gorgias-chat-container')
10 ?.querySelector('#chat-button')
11 ?.contentWindow.document.querySelector('head');
12 if (!chatButtonHead || ![...chatButtonHead.children].some(x => x.getAttribute('data-emotion'))) {
13 return;
14 }
15 clearInterval(timer);
16
17 var buttonStyle = document.createElement('style');
18 buttonStyle.textContent = '#gorgias-chat-messenger-button { background-color: orange; }';
19 chatButtonHead.appendChild(buttonStyle);
20 }, 50);
21})
22

Add custom CSS to the chat window

This script injects CSS into the chat window iframe after the visitor opens the chat. Replace the content of chatStyle.textContent with your own CSS rules:

1var initGorgiasChatPromise = (window.GorgiasChat)
2 ? window.GorgiasChat.init()
3 : new Promise(function (resolve) {
4 window.addEventListener('gorgias-widget-loaded', function () { resolve(); })
5 });
6
7initGorgiasChatPromise.then(function () {
8 GorgiasChat.on('widget:opened', function () {
9 var timer = setInterval(function () {
10 var chatWindowHead = document.querySelector('#gorgias-chat-container')
11 ?.querySelector('#chat-window')
12 ?.contentWindow.document.querySelector('head');
13 if (![...chatWindowHead?.children].some(x => x.getAttribute('data-emotion'))) {
14 return;
15 }
16 clearInterval(timer);
17
18 var chatStyle = document.createElement('style');
19 chatStyle.textContent = '.card-header h2 { color: #FF0000 !important; }';
20 chatWindowHead.appendChild(chatStyle);
21 }, 50);
22 })
23})
24

Replace the chat window background gradient with a solid color

To use a single flat color throughout the chat window instead of the default gradient, replace #xxxxxx with your hex color code:

1var initGorgiasChatPromise = (window.GorgiasChat)
2 ? window.GorgiasChat.init()
3 : new Promise(function (resolve) {
4 window.addEventListener('gorgias-widget-loaded', function () { resolve(); })
5 });
6
7initGorgiasChatPromise.then(async () => {
8 GorgiasChat.on('widget:opened', function () {
9 const chatWindow = document.querySelector('#chat-window')
10 ?.contentWindow.document.querySelector('.frame-content')
11 ?.firstChild.firstChild
12 if (chatWindow) {
13 chatWindow.style.background = '#xxxxxx';
14 }
15 })
16})
17

Replace the chat widget button with a custom element

This script hides the default chat button iframe and inserts a custom button in its place. Adjust the inline styles on myButton to match your design:

1var initGorgiasChatPromise = (window.GorgiasChat)
2 ? window.GorgiasChat.init()
3 : new Promise(function (resolve) {
4 window.addEventListener('gorgias-widget-loaded', function () { resolve(); })
5 });
6
7initGorgiasChatPromise.then(function () {
8 var timer = setInterval(function () {
9 var chatButtonHead = document.querySelector('#gorgias-chat-container')
10 ?.querySelector('#chat-button')
11 ?.contentWindow.document.querySelector('head');
12 if (!chatButtonHead?.children.length) {
13 return;
14 }
15 clearInterval(timer);
16
17 var chatButtonIframe = document.querySelector('#chat-button');
18 chatButtonIframe.style.display = 'none';
19
20 var myButton = document.createElement('button');
21 myButton.style.cssText = `
22 position: fixed;
23 right: 100px;
24 bottom: 10px;
25 z-index: 2147483000;
26 width: 50px;
27 height: 50px;
28 border-radius: 10px;
29 background-color: blue;
30 `;
31
32 myButton.onclick = function () {
33 if (GorgiasChat.isOpen()) {
34 GorgiasChat.close();
35 } else {
36 GorgiasChat.open();
37 }
38 };
39
40 document.body.appendChild(myButton);
41 }, 50);
42})
43

Fix z-index conflicts with other page elements

If the chat widget appears behind other elements on your page — an accessibility widget, a sticky header, a rewards popup — add this CSS to your site to bring it to the top of the stacking order:

1<style>
2#gorgias-chat-container iframe#chat-window,
3#gorgias-chat-container iframe#chat-campaigns {
4 z-index: 2147483647 !important;
5}
6#gorgias-chat-container iframe#chat-button {
7 z-index: 2147483646 !important;
8}
9</style>
10

If instead you want the chat to appear behind other elements:

1<style>
2#gorgias-chat-container iframe#chat-window,
3#gorgias-chat-container iframe#chat-campaigns {
4 z-index: 99 !important;
5}
6#gorgias-chat-container iframe#chat-button {
7 z-index: 99 !important;
8}
9</style>
10

Customizing widget text

Update the text labels used throughout the widget

The chat widget uses a dictionary of text strings for all UI labels — things like button text, placeholder copy, and status messages. You can override any of these by passing a partial or complete dictionary to GorgiasChat.updateTexts(). You only need to include the keys you want to change; everything else falls back to the default values.

To see all available text keys and their current values, run this in your browser console while the chat is loaded on the page:

1window.GorgiasChat.printLabelDictionary()
2

To override specific values, pass only the keys you want to change:

1initGorgiasChatPromise.then(function () {
2 GorgiasChat.updateTexts({
3 chatWithUs: 'Talk to us',
4 inputPlaceholder: 'Type your question here...',
5 headerText: 'Acme Support Team',
6 })
7})
8

If you have AI Agent automation features enabled on chat, use GorgiasChat.updateSSPTexts() to customize automation-specific labels such as order management copy, tracking labels, and self-service portal text. Run window.GorgiasChat.printLabelDictionary() to see both the texts and sspTexts dictionaries and identify the keys you want to change.

When the chat is offline, customers see a contact form. The message shown when they submit it is controlled by the contactFormEndingMessage text key. You can use HTML to add a link to your Help Center in that message:

1initGorgiasChatPromise.then(function () {
2 GorgiasChat.updateTexts({
3 contactFormEndingMessage: 'Thanks for your message, we will email you soon. In the meantime, visit our <a href="https://help.my-store.com">Help Center</a>.'
4 })
5})
6

Show or hide translation keys (developer tool)

To display raw translation keys in the chat UI instead of rendered text — useful for identifying which key controls which label — run this in your browser console:

1window.GorgiasChat.showTranslationKeys(true)
2

To go back to rendered text values:

1window.GorgiasChat.showTranslationKeys(false)
2


Was this article helpful?
Yes
No