Advanced chat customization

Updated 5 days ago by Tamara Zaric

If you would like to further customize the chat widget, you can follow the instructions below. However, you may first want to check out this guide on how to set up some basic chat customization.

This article is meant to serve simply as a reference point for you and your team and following these instructions will require knowledge of HTML, JavaScript, and Shopify Liquid if you use Shopify.

If you're using BigCommerce, please keep in mind that BC has a 'Manage Code' feature that allows you to place only <script> codes. This means that you will be able to place the default chat code and only a few other customization codes there.
For any non-script codes, like the one that changes the z-index in the style, you have to go into their 'Theme Manager → Edit Theme' and find the home.html file.

Disclaimer: The suggestions below are not formally features of our chat widget, but suggestions on how to further customize it. As such, our support for these types of customization is limited.
We recommend for these steps to be performed by someone with a technical background as you're experimenting with the chat set-up.

How to find and access theme.liquid files

Every code snippet used to customize the widget should be placed just below the chat installation script between the ‘<body>’ and ‘</body>’ tag. To find the script and place any custom code, you will need to find your Shopify store's theme.liquid files. Here’s how to get there:

  1. From the Shopify admin, go to Online Store → Themes.
  2. Click Actions → Edit code.

Detailed instructions in Shopify’s FAQs here.

Additional instructions for Shopify
  1. Go to your Shopify store's theme.liquid to edit the code.
  2. Navigate to your Shopify home screen.
  3. Click on 'Online Store' on the left.
  4. Select Pages → The page where you want to add the link (Ex. Contact Us page).
  5. Add the code:
    1. Copy the code above (choose the code depending on what you want to do).
    2. In the text box under Content, click on the '<>' icon (it says 'Show HTML' on hover). This will switch your view from text only to HTML view.
    3. Paste the code.
  6. Edit the text (optional):
    1. Go back to the original view by clicking on the '<>' icon again.
    2. By default, it will say, 'Start a chat with our team!', but you may customize this text if you want to.
  7. Click 'Save'.

Using the Gorgias Chat JavaScript API

The Gorgias Chat Javascript API helps you configure and customize your chat in some pretty advanced ways. The Chat API is available in Javascript from the GorgiasChat object as a member of the Window Object.

Before you call any methods, you need to make sure the chat is fully initialized, this is done with the GorgiasChat.init() method:

// Make sure that Gorgias Chat code snippet is called before your advanced code:
<script id="gorgias-chat-widget-install-v2" src="https://config.gorgias.chat/gorgias-chat-bundle-loader.js?applicationId=XXX"></script>


// Advanced code:
<script>
GorgiasChat.init().then(function() {
// Use GorgiasChat API here, now that the chat is fully initialized.
})
</script>

You must never call GorgiasChat without the init().then(...) callback in an HTML script tag <script></script> because your script code might run before the chat is downloaded and initialized.

Advanced Personalization

Disable auto open

Except when using a mobile device, the chat window will auto open for returning customers if they left the chat window opened and their last visit was not more than 4 days ago. You can prevent this using the following method:

<script>
window.GORGIASCHAT_DISABLE_AUTO_OPEN = true
</script>

Remove 'Powered by Gorgias' branding

You can remove the 'Powered by Gorgias' branding using the following method:

<script>
gorgiasChat.init().then(async (chat) => {
chat.hidePoweredBy(true)
})
</script>

The branding is displayed in the chat and the chat campaigns.

If you want to add a link on your page to open the chat when clicked, use the code below:

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

Likewise, you can also have a link to close the chat:

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

Hiding the chat on mobile

To hide the chat on mobile, use the following method:

<script>
GorgiasChat.init().then(function() {
GorgiasChat.hideOnMobile(true) // true to hide on mobile, false to show on mobile.
})
</script>

Display the chat widget after some time spent on the website

To only display the chat after a certain amount of time, use the following method:

<script>
GorgiasChat.init().then(async function() {
var chatElem = document.getElementById("gorgias-chat-container")
chatElem.style.display = "none";

function sleep(seconds) {
return new Promise(resolve => setTimeout(resolve, seconds * 1000));
}

await sleep(5) // CHANGE THIS VALUE TO THE NUMBER OF SECONDS TO WAIT BEFORE SHOWING THE CHAT BUBBLE
chatElem.style.display = "";
})
</script>

Remove the chat outside business hours

The following method can be used to hide the chat outside your business hours:

<script>
GorgiasChat.init().then(function() {
GorgiasChat.hideOutsideBusinessHours(true) // true to hide when outside of business hours, false to show.
})
</script>

Set custom business hours

The following method can be used to set custom business hours for your chat:

<script>
GorgiasChat.init().then(function () {
// Edit business hours on the go, if `Hide chat outside of business hours` is enabled, the chat will automatically appear or disappear.
GorgiasChat.setCustomBusinessHours({
// Using a timezone from https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
// Day 1 represents Monday
timezone: "Australia/Sydney",
businessHours: [
{ days: [1, 2, 3], fromTime: "08:15", toTime: "17:50" },
{ days: [4, 5], fromTime: "08:15", toTime: "12:00" }
]
})
});
</script>

Adjust chat default text values

It is possible to adjust the hardcoded text values used by the chat. Simply update the values below in the dictionary containing the texts and insert the script in your HTML.

You can change the following hardcoded text values on the chat widget using the code below:

  • Online and offline introduction text
  • Message input placeholder
  • Email capture placeholder
  • Email capture input label
  • Email capture online trigger text
  • Email capture online thanks text
  • Email capture offline trigger text
  • Email capture offline thanks text
  • Email capture required email placeholder
  • Email capture required message placeholder
<script>
GorgiasChat.init().then(function() {
var chatDict = {
actionPostbackError: "An error occurred while processing your action. Please try again.",
backLabelBackAt: "Back online at {time}",
backLabelBackInAMinute: "Back in 1 minute",
backLabelBackInAnHour: "Back in 1 hour",
backLabelBackInDays: "Back in {value} days",
backLabelBackInHours: "Back in {value} hours",
backLabelBackInMinutes: "Back in {value} minutes",
backLabelBackOn: "Back on {weekday}",
backLabelBackTomorrow: "Back soon",
campaignClickToReply: "Click to reply",
clickToRetry: "Message not delivered. Click to retry.",
conversationTimestampHeaderFormat: "MMMM D",
emailCaptureInputLabel: "Get notified by email",
emailCaptureOfflineThanksText: "Thanks {email}! We'll get back to you shortly.",
emailCaptureOfflineTriggerText: "We're away, leave us your email and we'll respond shortly.",
emailCaptureOnlineThanksText: "Thanks! We'll email you at {email} if you leave.",
emailCaptureOnlineTriggerText: "Leave us your email and we will reply soon.",
emailCaptureOnlineTriggerTextShortly: "Leave us your email and we'll get back to you shortly.",
emailCapturePlaceholder: "your@email.com",
emailCaptureRequiredEmailPlaceholder: "Leave your email",
emailCaptureRequiredMessagePlaceholder: "Write your message",
emailCaptureThanksText: "Thanks for reaching out! You'll get replies here and in your email.",
emailCaptureTriggerBackOnlineAt: "We'll be back online at {time}",
emailCaptureTriggerBackOnlineOn: "We'll be back online on {weekday}",
emailCaptureTriggerTextBase: "Leave us your email and we'll get back to you.",
emailCaptureTriggerTypicalReplyDay: "We typically reply in a day.",
emailCaptureTriggerTypicalReplyHours: "We typically reply in a few hours.",
emailCaptureTriggerTypicalReplyMinutes: "We typically reply in a few minutes.",
fetchHistory: "Load more",
fetchingHistory: "Retrieving history...",
headerText: "Gorgias Team",
inputPlaceholder: "Type a message...",
introductionText: "How can we help?",
invalidFileError: "Only images are supported. Choose a file with a supported extension (jpg, jpeg, png, gif, or bmp).",
messageDelivered: "Delivered",
messageError: "An error occurred while sending your message. Please try again.",
messageIndicatorTitlePlural: "({count}) New messages",
messageIndicatorTitleSingular: "({count}) New message",
messageRelativeTimeDay: "{value}d ago",
messageRelativeTimeHour: "{value}h ago",
messageRelativeTimeJustNow: "Just now",
messageRelativeTimeMinute: "{value}m ago",
messageSending: "Sending...",
messageTimestampFormat: "h:mm A",
offlineIntroductionText: "We'll be back soon",
poweredBy: "Powered by",
poweredByGorgias: "Powered by Gorgias",
send: "Send",
shopClosed: "{shopName} is now closed. Agents might not be available.",
shopClosingInAMinute: "{shopName} is closing in 1 minute.",
shopClosingInLessThanAMinute: "{shopName} is closing in less than 1 minute.",
shopClosingSoon: "{shopName} is closing in {minutes} minutes.",
tapToRetry: "Message not delivered. Tap to retry.",
unsupportedActionType: "Unsupported action type.",
unsupportedMessageType: "Unsupported message type.",
usualReplyTimeDay: "Typically replies within a day",
usualReplyTimeHours: "Typically replies in a few hours",
usualReplyTimeMinutes: "Typically replies in a few minutes"
}

window.GORGIAS_CHAT_TEXTS = chatDict
GorgiasChat.updateTexts(chatDict)
})
</script>

You don't need to provide all the available text keys when updating the texts. You can provide us only the relevant custom texts, the rest will use the default text values.

If you have enabled the Self-service feature on the chat, you can use the following script, that allows adjusting both the Chat and Self-service wordings:

<script>
GorgiasChat.init().then(function() {
var chatDict = {
actionPostbackError: "An error occurred while processing your action. Please try again.",
backLabelBackAt: "Back online at {time}",
backLabelBackInAMinute: "Back in 1 minute",
backLabelBackInAnHour: "Back in 1 hour",
backLabelBackInDays: "Back in {value} days",
backLabelBackInHours: "Back in {value} hours",
backLabelBackInMinutes: "Back in {value} minutes",
backLabelBackOn: "Back on {weekday}",
backLabelBackTomorrow: "Back soon",
campaignClickToReply: "Click to reply",
clickToRetry: "Message not delivered. Click to retry.",
conversationTimestampHeaderFormat: "MMMM D",
emailCaptureInputLabel: "Get notified by email",
emailCaptureOfflineThanksText: "Thanks {email}! We'll get back to you shortly.",
emailCaptureOfflineTriggerText: "We're away, leave us your email and we'll respond shortly.",
emailCaptureOnlineThanksText: "Thanks! We'll email you at {email} if you leave.",
emailCaptureOnlineTriggerText: "Leave us your email and we will reply soon.",
emailCaptureOnlineTriggerTextShortly: "Leave us your email and we'll get back to you shortly.",
emailCapturePlaceholder: "your@email.com",
emailCaptureRequiredEmailPlaceholder: "Leave your email",
emailCaptureRequiredMessagePlaceholder: "Write your message",
emailCaptureThanksText: "Thanks for reaching out! You'll get replies here and in your email.",
emailCaptureTriggerBackOnlineAt: "We'll be back online at {time}",
emailCaptureTriggerBackOnlineOn: "We'll be back online on {weekday}",
emailCaptureTriggerTextBase: "Leave us your email and we'll get back to you.",
emailCaptureTriggerTypicalReplyDay: "We typically reply in a day.",
emailCaptureTriggerTypicalReplyHours: "We typically reply in a few hours.",
emailCaptureTriggerTypicalReplyMinutes: "We typically reply in a few minutes.",
fetchHistory: "Load more",
fetchingHistory: "Retrieving history...",
headerText: "Gorgias Team",
inputPlaceholder: "Type a message...",
introductionText: "How can we help?",
invalidFileError: "Only images are supported. Choose a file with a supported extension (jpg, jpeg, png, gif, or bmp).",
messageDelivered: "Delivered",
messageError: "An error occurred while sending your message. Please try again.",
messageIndicatorTitlePlural: "({count}) New messages",
messageIndicatorTitleSingular: "({count}) New message",
messageRelativeTimeDay: "{value}d ago",
messageRelativeTimeHour: "{value}h ago",
messageRelativeTimeJustNow: "Just now",
messageRelativeTimeMinute: "{value}m ago",
messageSending: "Sending...",
messageTimestampFormat: "h:mm A",
offlineIntroductionText: "We'll be back soon",
poweredBy: "Powered by",
poweredByGorgias: "Powered by Gorgias",
send: "Send",
shopClosed: "{shopName} is now closed. Agents might not be available.",
shopClosingInAMinute: "{shopName} is closing in 1 minute.",
shopClosingInLessThanAMinute: "{shopName} is closing in less than 1 minute.",
shopClosingSoon: "{shopName} is closing in {minutes} minutes.",
tapToRetry: "Message not delivered. Tap to retry.",
unsupportedActionType: "Unsupported action type.",
unsupportedMessageType: "Unsupported message type.",
usualReplyTimeDay: "Typically replies within a day",
usualReplyTimeHours: "Typically replies in a few hours",
usualReplyTimeMinutes: "Typically replies in a few minutes"
}

var sspDict = {
applyPromoCode: "Apply promo code",
april: "Apr",
articleRecommendationInputPlaceholder: "Need more help? Ask us a question!",
attemptedDelivery: "Attempted delivery",
august: "Aug",
backToHome: "Back To Home",
billingInformation: "Billing information",
cancel: "Cancel",
cancelFulfillment: "Cancel fulfillment",
cancelMessageDescription: "I'd like to cancel the following fulfillment",
cancelOrder: "Cancel an order",
canceled: "Canceled",
cancelled: "Cancelled",
cantSignIn: "Can't sign in?",
changeShippingAddress: "I'd like to change my shipping address",
checkSpamFolder: "If you can't find the verification email, please check your spam and junk folders.",
checkpointAttemptFail: "Failed attempt",
checkpointAvailableForPickup: "Available for pickup",
checkpointDelivered: "Delivered",
checkpointException: "Exception",
checkpointException_001: "Exception",
checkpointException_002: "Customer moved",
checkpointException_003: "Customer refused delivery",
checkpointException_004: "Delayed (Customs clearance)",
checkpointException_005: "Delayed (External factors)",
checkpointException_006: "Held for payment",
checkpointException_007: "Incorrect Address",
checkpointException_008: "Pick up missed",
checkpointException_009: "Rejected by carrier",
checkpointException_010: "Returning to sender",
checkpointException_011: "Returned to sender",
checkpointException_012: "Shipment damage",
checkpointException_013: "Shipment lost",
checkpointExpired: "Expired",
checkpointInTransit: "In transit",
checkpointInfoReceived: "Info received",
checkpointOrderPlaced: "Order placed",
checkpointOutForDelivery: "Out for delivery",
checkpointPending: "Pending",
codeExpiresIn: "Code expires in",
codeSentTo: "Code sent to",
codeWillExpire: "This code will expire in 10 minutes. If you didn't initiate this request, please let our support agents know.",
confirmed: "Confirmed",
createdAt: "Created at",
customerHasNoOrdersEmail: "No orders found for this email",
customerHasNoOrdersPhone: "No orders found for this phone number",
damagedInDelivery: "My order was damaged in delivery",
december: "Dec",
delivered: "Delivered",
deliveredAt: "at",
deliveredOn: "Delivered on",
deliveredVia: "Shipped via",
editOrder: "Edit order",
email: "Email",
errorFetchingOrders: "An error occurred while fetching your orders",
errorSendingReportIssue: "Something went wrong while sending the report issue.",
estimatedDelivery: "Estimated delivery",
etaProvidedBy: "ETA provided by",
expectToBeDeliveredBy: "by",
failedDelivery: "Failed delivery",
failedFulfillment: "Failed fulfillment",
failure: "Failure",
february: "Feb",
fillYourEmailToTalkToAnAgent: "Fill your email to talk to an agent",
findOrder: "Find your order",
fulfillment: "Fulfillment",
fulfillmentDetails: "Fulfillment details",
happyToHelp: "Happy to help, have a great day!",
hiFirstname: "Hi {{firstName}},",
howCanIHelp: "How can we help?",
iHaveTheFollowingIssue: "I have the following Issue:",
iWouldLikeToCancelTheFollowingOrder: "I'd like to cancel the following order",
iWouldLikeToReturnTheFollowingItems: "I'd like to return the following items",
inTransit: "In transit",
inTransitVia: "In-transit via",
incorrectOrder: "I did not receive the correct order",
invalidCode: "Invalid code",
invalidPhoneNumber: "Invalid phone number",
itemNames: "Item names",
itemsRequestedForReturn: "Items requested for return",
january: "Jan",
july: "Jul",
june: "June",
labelPrinted: "Label printed",
labelPurchased: "Label purchased",
lastUpdated: "Last updated",
learnMore: "Learn more",
lostOrderDetails: "Lost your order details? Talk to an agent",
manageYourOrders: "Manage your orders",
march: "Mar",
maxVerificationAttemptsReached: "Maximum verification attempts reached",
may: "May",
needHelp: "Need more help?",
noCustomerAssociatedEmail: "No customer associated with this email",
noCustomerAssociatedPhone: "No customer associated with this phone number",
noINeedMoreHelp: "No, I need more help",
november: "Nov",
october: "Oct",
oneItemSelected: "1 item selected",
order: "Order",
orderCreated: "Order Created",
orderNotFound: "We have no record of that order number and email combination. Please try again or ",
orderNumber: "Order number",
orderPlaced: "Order placed",
other: "Other",
outForDelivery: "Out for delivery",
outForDeliveryVia: "Out for delivery via",
partiallyRefunded: "Partially refunded",
pastDeliveryDate: "I'm past my expected delivery date",
payment: "Payment",
pendingDelivery: "Pending delivery",
pleaseRefreshPageToUseChat: "Please refresh your page to continue using the chat.",
pleaseUseVerificationCodeToLogIn: "Please use this verification code to complete your log-in:",
previousConversation: "Previous Conversation",
processing: "Processing",
processingFulfillment: "Processing fulfillment",
provideEmailAndOrderNumber: "You must provide an email and an order number",
quantityToReturn: "Quantity to return",
quickAnswers: "Quick answers",
readyForPickup: "Ready for pickup",
reasonCancelOrder: "I'd like to cancel my order",
reasonCancelSubscription: "I'd like to cancel my subscription",
reasonChangeDeliveryDate: "I'd like to change the delivery date",
reasonChangeShippingAddress: "I'd like to change my shipping address",
reasonDidNotReceiveRefund: "I didn't get my refund",
reasonDiscountNotWorking: "My discount code is not working",
reasonEditOrder: "I'd like to edit my order",
reasonEditSubscription: "I'd like to edit my subscription",
reasonExchangeRequest: "I'd like to exchange items in my order",
reasonForgotToUseDiscount: "I forgot to apply my discount code",
reasonIncorrectItems: "The items are different from what I ordered",
reasonItemsMissing: "Some items are missing from my order",
reasonNotHappy: "I'm not happy with the product I received 👎",
reasonOrderDamaged: "My order was damaged in delivery",
reasonOrderDefective: "The items in my order are defective",
reasonOrderStillNotShipped: "My order should have shipped by now",
reasonOrderStuckInTransit: "My order has been stuck in transit",
reasonOther: "Other",
reasonPastExpectedDeliveryDate: "I'm past my expected delivery date",
reasonReorderItems: "I'd like to reorder some items",
reasonReplaceItemsRequest: "I'd like to replace items in my order",
reasonRequestDiscount: "I'd like a discount code",
reasonRequestRefund: "I'd like to get a refund for this order",
reasonReturnProduct: "I'd like to return a product",
reasonVeryHappy: "I'm very happy with the product I received 👍",
reasonWhereIsMyOrder: "Where is my order?",
refunded: "Refunded",
reportAnIssueWithOrder: "Report an issue with an order",
reportIssue: "Report issue",
requestCancellation: "Request Cancellation",
requestReturn: "Request Return",
resendCode: "Resend code",
return: "Return",
returnItems: "Return items",
returnOrder: "Return an order",
see1MoreItem: "1 more item",
see1MoreOrder: "See 1 more order",
seeMoreItems: "{moreItemsCount} more items",
seeMoreOrders: "See {nextPageOrderCount} more orders",
seeOrders: "See your orders",
selectAll: "Select all",
sendCode: "Send code",
sendUsAMessage: "Send us a message",
sent: "Sent",
september: "Sept",
severalItemsSelected: "{itemsSelectedCount} items selected",
shipmentBeingDelivered: "Order shipment is being delivered to its final destination.",
shipping: "Shipping",
shippingAddress: "Shipping address",
shippingInformation: "Shipping information",
showLessItems: "Show less",
signIn: "Sign in",
sincerely: "Sincerely,",
sms: "SMS",
sorryToHearThatEmailNotRequired: "Sorry to hear that! Someone will be with you soon.",
sorryToHearThatEmailRequired: "Sorry to hear that. Leave us your email and we'll get back to you.",
sorryToHearThatOfflineEmailCaptured: "Sorry to hear that, we'll get back to you by email.",
sorryToHearThatOnlineEmailCaptured: "I'm sorry to hear that. An agent will be with you in a few minutes.",
startConversation: "Start conversation",
stuckInTransit: "My order has been stuck in transit for several days",
subtotal: "Subtotal (Inc. tax)",
summary: "Summary",
supportTeam: "The {{shopFriendlyName}} support team",
talkToLiveAgent: "talk to a live agent",
thanksOurTeamWillRespond: "Thanks, our team will respond shortly.",
total: "Total",
track: "Track",
trackOrder: "Track an order",
trackingNumber: "Tracking number",
trackingNumberPrefix: "Tracking no.",
trackingUrl: "Tracking Url",
trySigningInWithOrderNumber: "Try signing in with order number",
unavailable: "Unavailable",
unfulfilled: "Unfulfilled",
verificationCodeField: "6-digit code",
wasThisHelpful: "Was this helpful?",
whatIsWrongWithOrder: "What is wrong with your order?",
yesThankYou: "Yes, thank you",
youWillGetRepliesByEmail: "Thanks! You'll get replies by email.",
youWillGetRepliesHereAndByEmail: "Thanks! You'll get replies here and by email.",
yourEmail: "Your email",
yourOrders: "Your orders",
yourPhoneNumber: "Your phone number"
}

window.GORGIAS_CHAT_TEXTS = chatDict
GorgiasChat.updateTexts(chatDict)
GorgiasChat.updateSSPTexts(sspDict)
})
</script>

Instructions for Shopify:

  1. Go to your Shopify's theme.liquid to edit the code.
    1. Navigate to your Shopify home screen.
    2. Click on 'Online Store' on the left.
    3. Select ThemesActionsEdit code.
    4. Under Layout, choose theme.liquid.
  2. Add the code:
    1. Copy the code above.
    2. Paste the code at the last line of the text code box.
  3. Edit the text of the item that you want to change.
    1. For example, you want to edit the message input placeholder ("Type a message...").
      1. If you want to change this, erase the text between the quotation marks.
  4. Click 'Save'.

Display currently used text values

If you wish to display the current text values, run the following in the console:

window.GorgiasChat.printLabelDictionary()

Toggle the display of translation keys/text values in the chat

If you wish to display the translation keys in the chat instead of the text values, run the following in the console:

window.GorgiasChat.showTranslationKeys(true)

In a similar fashion, you can go back to text values with the following code:

window.GorgiasChat.showTranslationKeys(false)

Add custom CSS

If you wish to customize the visual aspect of the chat widget, you can add additional CSS rules to each of the three following sections: the chat button, chat window, and chat campaigns.

Add the following script to your web page where the chat is installed and modify the lines xxxStyle.textContent = '...', replacing the content with your own CSS rules:

// Use this script to customize the chat button.
<script>
GorgiasChat.init().then(function () {

var timer = setInterval(function () {
var chatButtonHead = document.querySelector('#gorgias-chat-container')?.querySelector('#chat-button')?.contentWindow.document.querySelector('head');
if (![...chatButtonHead?.children].some(x => x.getAttribute("data-emotion"))) {
return;
}
clearInterval(timer);

var buttonStyle = document.createElement('style');
buttonStyle.textContent = '#gorgias-chat-messenger-button {background-color: orange; transition: background-color 200ms ease;}'; // the custom CSS for the chat button
chatButtonHead.appendChild(buttonStyle);
}, 50);
})
</script>


// Use this script to customize the chat window.
<script>
GorgiasChat.init().then(function () {
GorgiasChat.on('widget:opened', function () {
var timer = setInterval(function () {
var chatWindowHead = document.querySelector('#gorgias-chat-container')?.querySelector('#chat-window')?.contentWindow.document.querySelector('head');
if (![...chatWindowHead?.children].some(x => x.getAttribute("data-emotion"))) {
return;
}
clearInterval(timer);

var chatStyle = document.createElement('style');
chatStyle.textContent = '.message-window-iframe-1g7otri {box-shadow: none; background-color: lawngreen}'; // window header green
chatWindowHead.appendChild(chatStyle);
}, 50);
})

})
</script>

Replace the chat widget button

You have the ability to replace our chat widget button with your own by providing some custom code. The following custom script would replace the original widget button with a custom button element.

<script>
GorgiasChat.init().then(function () {
var timer = setInterval(function () {
var chatButtonHead = document.querySelector('#gorgias-chat-container')?.querySelector('#chat-button')?.contentWindow.document.querySelector('head');
if (!chatButtonHead?.children.length) {
return;
}
clearInterval(timer);

var chatButtonIframe = document.querySelector('#chat-button');
chatButtonIframe.style = "display:none;"

// replace our button with your own var myButton = document.createElement('button');
myButton.style = `
position: fixed;
right: 100px; bottom: 10px;
z-index: 2147483000;
width: 50px;
height: 50px;
border-radius: 10px;
background-color: blue;
`

// onClick, behave like a chat opener
myButton.onclick = function () {
if (GorgiasChat.isOpen()) {
GorgiasChat.close();
} else {
GorgiasChat.open();
}
}
document.body.appendChild(myButton);
}, 50);
});
</script>

Chat interactions with JavaScript

Configuring the chat with URL query parameters

You may configure the chat behavior with URL query parameters to share such links with your customers.

Let's assume that your store's URL is www.my-store.com:

Opening the chat automatically

You can make the chat open automatically on page load by adding the gs_open_chat parameter to your URL (notice the gs_ which stands for 'gorgias'). The resulting store URL is now www.my-store.com?gs_open_chat.

Setting the default chat page

You can set up a chat page that will be showing by default for your customers with the query parameter gs_chat_page. The value can be either conversation (for the chat messages page) or homepage (for the self-service page, to fall back to the chat messages page if self-service is disabled).

For instance, www.my-store.com?gs_chat_page=conversationsets the conversation page as the default one. www.my-store.com?gs_chat_page=homepage sets the self-service page as the default one.

Pre-filling the user message

You can direct your customers to a URL where the chat will have a pre-filled message by using the query parameter gs_chat_message=mymessagewhere 'mymessage' is your custom message. Note that the message must be URL encoded. For example, the message 'I want information on product...' must be URL-encoded as I%20want%20information%20on%20product....

The resulting URL to your store would be www.my-store.com?gs_chat_message=I%20want%20information%20on%20product...

You can use online tools to encode a string such as urlencoder.org.

Using more than one parameter at the same time

Let's say that you want to open the chat automatically, and also set the default page as conversation, and pre-fill the user message with 'Hello'. You can combine all the parameters together in a single URL by separating them with an '&'.

For instance: www.my-store.com?gs_open_chat&gs_chat_page=conversation&gs_chat_message=Hello

You are now ready to share these links with your users!

Pre-fill the user message

If you want to pre-fill the user message input field, you can use the following method with a string parameter:

<script>
GorgiasChat.init().then(function() {
GorgiasChat.setCurrentInput('Hello !')
})
</script>

Check if the chat is open or closed

You may use the following method to determine whether the chat is in an open or closed state:

<script>
GorgiasChat.init().then(function() {
GorgiasChat.isOpen() // Will return true or false.
})
</script>

Check whether the current time is in business hours

You may use the following method to determine whether the chat business hours (as defined in the helpdesk) are displayed correctly. Please just keep in mind that this variable is only trustworthy after chat initialization:

<script>
GorgiasChat.init().then(function() {
GorgiasChat.isBusinessHours() // Will return true or false.
})
</script>

Disable the Self-service Portal

If you have the self-service features enabled, but you wish to hide self-service on certain pages, it is possible to add the following script to disable the Self-service Portal:

<script>
GorgiasChat.init().then(function() {
GorgiasChat.disableSSP()
})
</script>

Set the current page of the chat

You can change the current page of the chat with this method:

<script>
GorgiasChat.init().then(function() {
// To show the conversation page.
GorgiasChat.setPage('conversation')

// To show the self-service screen.
GorgiasChat.setPage('homepage') // Note that the conversation page is showed if the self-service is disabled.
})
</script>

Subscribe to chat events

Sometimes it's useful to do something specific when the chat widget is open or closed. You can use the example below to do that.

<script>
GorgiasChat.init().then(function() {
GorgiasChat.on('EVENT_NAME', function(data) {
// your code should go here
})
})
</script>

Gorgias Chat supports the following events:

  • A ready event is triggered when the chat is rendered.
  • A destroy event is triggered when the chat is unmounted.
  • A message:received event is triggered when a message is received. The data parameter will contain the message attributes.
  • A message:sent event is triggered when a message is received. The data parameter will contain the message attributes.
  • A message event is triggered when a message is sent or received. The data parameter will contain the message attributes.
  • An unreadCount event is triggered when the unread message count changes. The data parameter will contain the new number of unread messages.
  • A widget:opened event is triggered when the chat window is opened.
  • A widget:closed event is triggered when the chat window is closed.
  • A connected event is triggered when a connection to the chat server is established.
  • A disconnected event is triggered when a connection to the chat server is lost.
  • A typing:start event is triggered when an agent begins typing their message.
  • A typing:stop event is triggered when an agent stops typing their message.

It is also possible to deregister an event listener using the GorgiasChat.off('EVENT_NAME', listener). The listener argument must be the function that was previously registered to subscribe to the event.

Programmatically send a message

To send a message from the user via the chat programmatically, you may use this method with a string parameter:

<script>
GorgiasChat.init().then(function() {
GorgiasChat.sendMessage('the message')
})
</script>

Note that if the chat is still closed, the message will wait for the user to open the chat before sending. If the chat remains always closed, the message will never be sent. If you want to send a message no matter what, force the opening of the chat first with GorgiasChat.open().

Programmatically capture an email

You may want to set up the shopper's email programmatically. To do so, we exposed the captureUserEmail method that allows you to change the user email associated to the current chat conversation.

<script>
GorgiasChat.init().then(function() {
GorgiasChat.captureUserEmail('user@example.com');
})
</script>

Programmatically capture the Shopify cart

You may want to link a specific cart with the current chat user. To do so, we expose the captureShopifyCart method that allows you to provide the Shopify Cart of the Shopify user currently using the chat. The cart details will be displayed in the sidebar of the ticket on the helpdesk application.

<script>
async function getCart(url = '/cart.json') {
const response = await fetch(url, {
method: 'GET',
});
return response.json();
}

GorgiasChat.init().then(function() {
getCart().then(function(cart) {
GorgiasChat.captureShopifyCart(cart);
});
})
</script>

Additional features

Disable Segment

To disable Segment (a script used to gather analytics) use the following script:

<script>
GorgiasChat.init().then(function() {
GorgiasChat.disableSegment()
})
</script>

Note that it should be placed at the top of the customisation scripts, so that the script doesn't get triggered by another API request.
Remove the chat based on country code
This feature requires an ipstack account. Free accounts are limited to 5,000 requests. If you exceed this limit, you will need to upgrade to a paid account.

If you only work with certain countries you might want to only handle chat messages coming from those countries. The code below hides the chat for ALL countries except United States (US) and Mexico (MX):

<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script>
// set your ipstack API key
var ipstackAPIKey = 'YOUR_API_KEY'
// set your country code whitelist
var countryCodeWhiteList = ['US', 'MX']
// set this to false if you only have a free tier account for ipstack
var useHttps = true

function removeGorgiasChat(countryCode) {
GorgiasChat.init().then(function() {
var container = document.querySelector('#gorgias-chat-container');
if (container && !countryCodeWhiteList.includes(countryCode)) {
container.remove()
}
})
}

var countryCode = window.localStorage.getItem('countryCode')
if (!countryCode) {
protocol = useHttps ? 'https' : 'http'
$.ajax({
url: protocol + '://api.ipstack.com/check?access_key=' + ipstackAPIKey + '&fields=country_code',
dataType: 'jsonp',
success: function (json) {
if (json && json.country_code) {
countryCode = json.country_code
} else {
countryCode = 'unknown'
}
window.localStorage.setItem('countryCode', countryCode)
removeGorgiasChat(countryCode)
},
error: function (request, status, error) {
console.error(request.responseText);
window.localStorage.setItem('countryCode', 'unknown')
removeGorgiasChat('unknown')
}
})
} else {
removeGorgiasChat(countryCode)
}
</script>

Instructions for Shopify:

  1. Go to your Shopify store's theme.liquid to edit the code.
    1. Navigate to your Shopify home screen.
    2. Click on 'Online Store' on the left.
    3. Select ThemesActionsEdit code.
    4. Under Layout, choose theme.liquid.
  2. Add the code:
    1. Copy the code above and paste it on the code text box.
    2. Enter your ipstack API key where the code says 'YOUR_API_KEY'.
    3. Enter the country code/s where you only want to display the chat widget where it says ['US', 'MX'].
    4. In the part where it says 'var useHttps = true', change it from 'true' to 'false' if you're using a free account on ipstack. Otherwise, feel free to just leave it be.
  3. Click on 'Save'. The chat won't be available to anyone except for shoppers from the countries you entered.

Troubleshooting

Uncaught ReferenceError: GorgiasChat is not defined

This console error means that the Gorgias Chat code snippet is either missing in the page, or called after the custom script. Lastly, please verify that you are well using the Gorgias chat bundle loader version 2 by checking that you have gorgias-chat-widget-install-v2 in the script.

Uninstalling and reinstalling the Chat from Shopify using the One-click installation can cause this. Please review the theme files scripts order.
The chat is conflicting with other widgets

If your chat widget is conflicting or is hidden behind some other elements on the page, like the accessibility widget, rewards widget, etc., changing the z-index should overlay the chat on top of any other element. To do this, add this code to your site:

<style>
#gorgias-chat-container iframe#chat-window,
#gorgias-chat-container iframe#chat-campaigns {
z-index: 2147483647 !important;
}
#gorgias-chat-container iframe#chat-button {
z-index: 2147483646 !important;
}
</style>

If you are using Shopify, the code needs to be added under theme.liquid files. It would be best if you add it somewhere close to the existent chat code, just for easier organization.

Instructions for Shopify:

  1. Go to your Shopify store's theme.liquid to edit the code.
    1. Navigate to your Shopify home screen.
    2. Click on 'Online Store' on the left.
    3. Select ThemesActionsEdit Code.
    4. Under Layout, choose theme.liquid.
  2. Add the code:
    1. Copy the code above.
    2. Paste it on the first line or the last line in the text code box.
  3. Click 'Save'. The chat widget should not be hidden now.

Hope this helps you master some code and turn your chat widget into a custom-built tool that will get your customer service to the next level! As always, our Support Team is here for you if you have any follow-up questions, so please feel free to reach out via our live chat or email at support@gorgias.com.


What do you think? Yay or Nay?