Skip to content

Instantly share code, notes, and snippets.

@webhasan
Created March 30, 2024 06:37
Show Gist options
  • Save webhasan/c53019829373e0deb85b5b080d8126db to your computer and use it in GitHub Desktop.
Save webhasan/c53019829373e0deb85b5b080d8126db to your computer and use it in GitHub Desktop.
Shopify Chat
<script>
(function() {
var trackedChatClick = false;
var customerFormSubmit = false;
var foundCustomerForm = false;
var foundChatButton = false;
var startChat = false;
function captureChatStart() {
var shadowRoot = document.getElementById('ShopifyChat').shadowRoot;
var messageSubmitButton = shadowRoot.querySelector('button[data-spec="message-submit"]');
if(messageSubmitButton && !foundChatButton) {
console.log('chat button', messageSubmitButton);
foundChatButton = true;
messageSubmitButton.addEventListener('click', function() {
if(!startChat) {
startChat = true;
dataLayer.push({
event: 'shopify_chat_start'
})
}
})
}
}
function captureUserInfo() {
var shadowRoot = document.getElementById('ShopifyChat').shadowRoot;
var formInsideShadowRoot = shadowRoot.querySelector('form[name="customerInfoFormSubmit"]');
if(formInsideShadowRoot && !foundCustomerForm) {
console.log('chat form', formInsideShadowRoot);
foundCustomerForm = true;
formInsideShadowRoot.addEventListener('submit', function(event) {
if(!customerFormSubmit) {
customerFormSubmit = true;
var firstNameEl = shadowRoot.querySelector('input[placeholder="First Name"]');
var lastNameEl = shadowRoot.querySelector('input[placeholder="Last Name"]');
var emailEl = shadowRoot.querySelector('input[placeholder="Email Address"]');
dataLayer.push({
event: 'shopify_chat_user_info_submit',
customerInfo: {
first_name: firstNameEl.value,
last_name: lastNameEl.value,
email: emailEl.value,
}
});
}
});
}
}
document.addEventListener('click', function(event) {
var chatEl = event.target.closest('#ShopifyChat');
if(chatEl && !trackedChatClick) {
trackedChatClick = true;
dataLayer.push({
event: 'shopify_chat_click',
})
}
captureChatStart();
captureUserInfo();
});
})();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment