Customize the Gorgias chat widget with extra codeUpdated 8 minutes ago
Who can use this feature?
Most chat customization happens in your chat settings, without code. There, you can customize the chat's appearance, control when and where chat appears, and rewrite the chat's copy in each language. Gorgias supports and maintains everything you set there.
The snippets in this article go beyond those settings. They use the chat widget's JavaScript API to do things the settings don't offer, like showing the chat only on certain pages, opening it from your own button, or reacting to chat events. A developer adds them to your store's theme once, as described in Set up custom code, then adapts the snippets they need. Instructions in this article use Shopify. On other platforms, a developer can apply the same approach.
If you came here from your chat's language settings (Settings > Chat > your chat > Language): any text or label changes you make with code override the copy you set there. To change it with code, go to Update the text labels used throughout the widget.
Before you use these snippets
- These are examples, not built-in features. They show ways to extend the chat widget. When a setting covers what you need, use the setting instead, because Gorgias maintains it for you.
- Have a developer add and maintain them. Each snippet needs adapting to your store and testing on your site. You're responsible for any code you add, including fixing it if it affects your store.
- Gorgias support can't troubleshoot, adapt, or write custom code. We can confirm whether the chat widget itself is working as expected. For help implementing a customization, work with your developer or a Gorgias Service Partner.
- Snippets can stop working when the widget changes. We review these examples and update or remove them when that happens, but we can't guarantee they'll keep working. Snippets in Change how the widget looks depend on the widget's internal structure and are the most likely to break.
GorgiasChat.getBundleVersion() in your browser console.Snippets in this article
- Set up custom code
- Use URL parameters
- Set window variables before the widget loads
- Control where and when the chat appears
- Control the widget programmatically
- Respond to chat events
- Work with business hours
- Associate an email address with a chat session
- Turn off Segment tracking
- Change the text in the widget
- Change how the widget looks
- Frequently asked questions
Set up custom code
Every snippet in this article runs from your store's theme, so your developer adds the code in one place that every page loads. This works whether you installed chat with Quick install for Shopify or manually.
Add your code to your Shopify theme
- From your Shopify admin, go to Online Store > Themes.
- Next to your current theme, click , then select Edit code.
- Under Layout, open theme.liquid.
- Paste your
<script>tag just before the closing</body>tag. If you installed chat manually, paste it after the Gorgias installation snippet. - Click Save.
Code in theme.liquid runs on every page. To run a snippet on certain pages only, check the page path in your script, as in Hide the chat on specific pages.
Wait for the widget to load
Every snippet that uses the GorgiasChat object, the widget's JavaScript API, has to wait until the widget is ready. The widget loads in the background, so your script can run before or after it. Use this wrapper to handle both cases:
1var initGorgiasChatPromise = (window.GorgiasChat)2 ? window.GorgiasChat.init()3 : new Promise(function (resolve) {4 window.addEventListener('gorgias-widget-loaded', function () { resolve(); })5 });67initGorgiasChatPromise.then(function () {8 // Your custom code goes here9});10
If the widget has already loaded, the wrapper calls init() right away. If it hasn't, the wrapper waits for the gorgias-widget-loaded event. Define initGorgiasChatPromise once per page, then put each snippet's code inside initGorgiasChatPromise.then(...).
Don't call GorgiasChat methods outside the wrapper. If your code runs before the widget loads, the browser console shows "Uncaught ReferenceError: GorgiasChat is not defined" and your code doesn't run.
Use URL parameters
Some behaviors can be triggered by adding a parameter to any page URL on your site, with no JavaScript.
Open the chat automatically on page load by adding gs_open_chat to the URL:
1https://www.my-store.com?gs_open_chat2
Pre-fill the chat input field by adding gs_chat_message to the URL. The message must be URL-encoded, so spaces become %20:
1https://www.my-store.com?gs_chat_message=I%20have%20a%20question%20about%20my%20order2
Navigate the chat to a specific view on load by adding gs_chat_page to the URL. Valid values are:
conversation: the live chat view if agents are online, or the offline contact form if notchat: always the live chat view, whatever the online statushomepage: the AI Agent automation features home screen, or the live chat view if automation features aren't turned on
1https://www.my-store.com?gs_chat_page=conversation2
Combine parameters by separating them with &. For example, to open the chat, go to the conversation view, and pre-fill a message:
1https://www.my-store.com?gs_open_chat&gs_chat_page=conversation&gs_chat_message=Hello2
Set window variables before the widget loads
These settings are read once, when the widget starts, so they must be set before it loads. Place them in the <head> section of theme.liquid, not before </body>. If you installed chat manually, they must also come before the Gorgias installation snippet. They don't use the GorgiasChat object or the wrapper.
Stop the chat from reopening for returning visitors. By default, on desktop, the chat window opens automatically for visitors who had it open in the last 4 days. To turn this off:
1<script>2 window.GORGIASCHAT_DISABLE_AUTO_OPEN = true3</script>4
Keep your exact font color. The chat adjusts font and icon colors against your background color to keep them readable. To keep your configured font color instead:
1<script>2 window.GORGIASCHAT_DISABLE_CONTRAST_COLOR = true3</script>4
Control where and when the chat appears
Hide the chat on specific pages
If you installed chat with Quick install for Shopify, you can hide it on specific pages from your chat's Installation settings without code. Use this snippet if you installed chat manually or need logic the setting doesn't cover.
Replace the paths in pathsToHide with the pages where you want the chat hidden. Use the path only, without your domain or any query string:
1var pathsToHide = [2 '/cart',3 '/pages/contact',4];56initGorgiasChatPromise.then(function () {7 var currentPath = window.location.pathname.replace(/\/$/, '') || '/';8 if (pathsToHide.includes(currentPath)) {9 GorgiasChat.hideChat(true);10 }11});12
Display the chat after a time delay
To give visitors a moment on the page before the chat appears, hide it on load and show it after a delay. Change 5000 to the number of milliseconds to wait (5000 is 5 seconds):
1initGorgiasChatPromise.then(function () {2 GorgiasChat.hideChat(true);34 setTimeout(function () {5 GorgiasChat.hideChat(false);6 }, 5000);7});8
Hide the chat based on the visitor's country
This snippet works on Shopify stores only. It uses the country Shopify has set for the visitor's session, from Shopify Markets or a country selector on your store, so it needs no third-party service or API key. Because it uses Shopify Liquid, it must go in theme.liquid (see Add your code to your Shopify theme), not in a separate JavaScript file.
Update allowedCountries with the two-letter country codes where you want the chat to appear:
1<script>2 var visitorCountry = '{{ localization.country.iso_code }}';3 var allowedCountries = ['US', 'CA'];45 var initGorgiasChatPromise = (window.GorgiasChat)6 ? window.GorgiasChat.init()7 : new Promise(function (resolve) {8 window.addEventListener('gorgias-widget-loaded', function () { resolve(); })9 });1011 initGorgiasChatPromise.then(function () {12 if (!allowedCountries.includes(visitorCountry)) {13 GorgiasChat.hideChat(true);14 }15 });16</script>17
Control the widget programmatically
Open or close the chat from your own button
To open the chat from a button anywhere on your page, give the button an ID and attach the click handler once the widget is ready:
1<button type="button" id="open-gorgias-chat">Chat with our team</button>23<script>4 initGorgiasChatPromise.then(function () {5 document.getElementById('open-gorgias-chat').addEventListener('click', function () {6 GorgiasChat.open();7 });8 });9</script>10
To close the chat instead, call GorgiasChat.close().
Check whether the chat is open
GorgiasChat.isOpen() returns true if the chat window is open and false if it isn't:
1initGorgiasChatPromise.then(function () {2 if (GorgiasChat.isOpen()) {3 // Your code for when the chat is open4 }5});6
Pre-fill the message input field
To fill the chat input field with text that the visitor can edit before sending:
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 the visitor's behalf:
1initGorgiasChatPromise.then(function () {2 GorgiasChat.sendMessage('I have a question about my order.');3});4
The message waits until the visitor opens the chat, so if they never open it, it's never sent. To send it right away, open the chat first:
1initGorgiasChatPromise.then(function () {2 GorgiasChat.open();3 GorgiasChat.sendMessage('I have a question about my order.');4});5
Navigate the chat to a specific view
GorgiasChat.setPage() takes the same values as the gs_chat_page URL parameter: 'conversation', 'chat', or 'homepage'. See Use URL parameters for what each one does.
1initGorgiasChatPromise.then(function () {2 GorgiasChat.setPage('conversation');3});4
Respond to chat events
Use GorgiasChat.on() to run code when something happens in the chat. Replace EVENT_NAME with one of the events below:
1initGorgiasChatPromise.then(function () {2 GorgiasChat.on('EVENT_NAME', function (data) {3 // Your code here4 });5});6
To stop listening, call GorgiasChat.off('EVENT_NAME', listener) with the same function you passed to on().
| Event | Fires when | data contains |
|---|---|---|
ready | The chat has rendered on the page | |
destroy | The chat is removed from the page | |
widget:opened | The chat window opens | |
widget:closed | The chat window closes | |
message:received | The visitor receives a message | The message |
message:sent | The visitor sends a message | The message |
message | Any message is sent or received | The message |
unreadCount | The number of unread messages changes | The new count |
connected | The chat connects to the chat server | |
disconnected | The chat loses its connection to the chat server | |
typing:start | An agent starts typing | |
typing:stop | An agent stops typing | |
campaign:opened | A chat campaign opens | |
campaign:closed | A chat campaign closes |
Work with business hours
Check whether the current time is within business hours
GorgiasChat.isBusinessHours() returns true during your business hours. It's only accurate after the widget has loaded:
1initGorgiasChatPromise.then(function () {2 if (GorgiasChat.isBusinessHours()) {3 // Your code for business hours4 }5});6
Set custom business hours via script
GorgiasChat.setCustomBusinessHours() replaces the business hours from your chat settings on the page where it runs. This is useful when your hours change often. Use a timezone name from the IANA time zone database, and number days from 1 (Monday) to 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 turned on in your chat settings, the chat appears and disappears based on these hours.
Associate an email address with a chat session
GorgiasChat.captureUserEmail() links an email address to the visitor's chat session, so their conversations are tied to the right customer. Use it when your site already knows the visitor's email, for example because they're logged in.
This example uses Shopify Liquid to get the logged-in customer's email, so place it in a Liquid theme file such as theme.liquid. On other platforms, replace customerEmail with however your site provides the email:
1<script>2 var customerEmail = '{{ customer.email }}';34 initGorgiasChatPromise.then(function () {5 if (customerEmail) {6 GorgiasChat.captureUserEmail(customerEmail);7 }8 });9</script>10
The widget throws an error if the value isn't a valid email address. It also rejects the placeholder [email protected].
Turn off Segment tracking
The chat widget uses Segment for analytics. To turn it off, for example to meet privacy requirements, call disableSegment(). Put it before your other customization scripts so it runs before anything else can send a tracking event:
1initGorgiasChatPromise.then(function () {2 GorgiasChat.disableSegment();3});4
Change the text in the widget
Update the text labels used throughout the widget
Every label in the widget, such as button text, placeholders, and status messages, comes from a list of text keys. To change a label, pass its key and your new text to GorgiasChat.updateTexts(). Include only the keys you want to change. Everything else keeps its default.
updateTexts() overrides the text you set in your chat's language settings.To see every key and its current value, run this in your browser console on a page where the chat is loaded:
1window.GorgiasChat.printLabelDictionary()2
Then pass the keys you want to change. This example changes the placeholder text in the message field:
1initGorgiasChatPromise.then(function () {2 GorgiasChat.updateTexts({3 inputInitialPlaceholder: 'Ask us about sizing, shipping, or returns',4 });5});6
If AI Agent automation features are turned on for chat, use GorgiasChat.updateSSPTexts() the same way to change automation labels, such as order management and tracking text. printLabelDictionary() lists these keys under sspTexts.
Add a hyperlink to your Help Center in the offline auto-reply
When the chat is offline, visitors see a contact form. The message they see after submitting it uses the contactFormEndingMessage key, which accepts HTML. To add a link to your Help Center:
1initGorgiasChatPromise.then(function () {2 GorgiasChat.updateTexts({3 contactFormEndingMessage: 'Thanks for your message, we\'ll 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
Which keys appear depends on the chat view the visitor is on. To find which key controls a label, show the raw keys in the chat instead of the text. Run this in your browser console:
1window.GorgiasChat.showTranslationKeys(true)2
To show the text again:
1window.GorgiasChat.showTranslationKeys(false)2
Change how the widget looks
The chat widget draws its button, window, and campaigns in separate frames (iframes). To add CSS inside a frame, a script has to wait until the frame's own styles have loaded, so the CSS snippets check for them every 50 milliseconds and stop after 10 seconds.
Add custom CSS to the chat button
Replace the CSS in buttonStyle.textContent with your own rules:
1initGorgiasChatPromise.then(function () {2 var attempts = 0;3 var timer = setInterval(function () {4 if (++attempts > 200) { clearInterval(timer); return; }56 var chatButtonHead = document.querySelector('#gorgias-chat-container #chat-button')7 ?.contentWindow?.document.querySelector('head');8 if (!chatButtonHead || ![...chatButtonHead.children].some(x => x.getAttribute('data-emotion'))) {9 return;10 }11 clearInterval(timer);1213 var buttonStyle = document.createElement('style');14 buttonStyle.textContent = '#gorgias-chat-messenger-button { background-color: orange; }';15 chatButtonHead.appendChild(buttonStyle);16 }, 50);17});18
Add custom CSS to the chat window
The chat window frame loads when the visitor opens the chat, so this snippet runs on each open and adds your styles once. This example changes the font of the message field. Replace the CSS in chatStyle.textContent with your own rules:
1initGorgiasChatPromise.then(function () {2 GorgiasChat.on('widget:opened', function () {3 var attempts = 0;4 var timer = setInterval(function () {5 if (++attempts > 200) { clearInterval(timer); return; }67 var chatWindowHead = document.querySelector('#gorgias-chat-container #chat-window')8 ?.contentWindow?.document.querySelector('head');9 if (!chatWindowHead || ![...chatWindowHead.children].some(x => x.getAttribute('data-emotion'))) {10 return;11 }12 clearInterval(timer);1314 if (chatWindowHead.querySelector('#custom-chat-window-style')) {15 return;16 }17 var chatStyle = document.createElement('style');18 chatStyle.id = 'custom-chat-window-style';19 chatStyle.textContent = 'textarea { font-family: Georgia, serif !important; }';20 chatWindowHead.appendChild(chatStyle);21 }, 50);22 });23});24
Replace the chat widget button with a custom element
This snippet hides the default chat button and adds your own button in its place. It hides the default button with a CSS rule because the widget rebuilds that button each time the chat closes. Adjust the styles on myButton to match your design:
1initGorgiasChatPromise.then(function () {2 var hideDefaultButton = document.createElement('style');3 hideDefaultButton.textContent = '#gorgias-chat-container iframe#chat-button { display: none !important; }';4 document.head.appendChild(hideDefaultButton);56 var myButton = document.createElement('button');7 myButton.type = 'button';8 myButton.setAttribute('aria-label', 'Open chat');9 myButton.style.cssText = `10 position: fixed;11 right: 100px;12 bottom: 10px;13 z-index: 2147483000;14 width: 50px;15 height: 50px;16 border-radius: 10px;17 background-color: blue;18 `;1920 myButton.addEventListener('click', function () {21 if (GorgiasChat.isOpen()) {22 GorgiasChat.close();23 } else {24 GorgiasChat.open();25 }26 });2728 document.body.appendChild(myButton);29});30
Fix z-index conflicts with other page elements
If the chat appears behind other elements on your page, such as an accessibility widget, a sticky header, or a rewards pop-up, add this CSS to your site to bring it to the front:
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
To put the chat behind other elements instead:
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
Frequently asked questions
Why does the console say "Uncaught ReferenceError: GorgiasChat is not defined"?
Your code called a GorgiasChat method before the widget loaded. Put the code inside the wrapper from Wait for the widget to load. If you use the wrapper and still see the error, check that chat is installed and appears on the page.
Can I add custom code if I installed chat with Quick install for Shopify?
Yes. Add your code to theme.liquid as described in Add your code to your Shopify theme. The wrapper waits for the widget however it was installed.