javascripthtmlshopifyliquidevent-listener

Clicking a Chat Div (role="button") from Another Button in Shopify (Liquid & JavaScript)


I have a button inside a Shopify Liquid file, and when it's clicked, I need it to trigger a click event on a chat div role=button elsewhere in the DOM.

<button class="my-button">open chat</button>

Chat Div role=button (Rendered in DOM):

<div class="chat-button" data-testid="launcher-button" role="button">

</div>

Issue: I attempted to use JavaScript to trigger the .chat-button when .my-button is clicked:

document.querySelector(".my-button").addEventListener("click", function () {
    document.querySelector(".chat-button")?.click();
});

However, the chat button is not always found or does not respond to the .click() event.

Questions: Is .chat-button dynamically loaded after the page renders? If so, how can I ensure it's ready before triggering .click()?

Is .click() the right approach for a , or should I use dispatchEvent(new Event("click"))?

If .chat-button is inside an iframe, how can I access and click it from my script?

Would appreciate any insights!

Notes: The button is a Front Chat Button


Solution

    1. Yes, if the chat button comes from the third-party app, you need to wait until that button is fully active on your storefront.
    2. You can make your button disabled for a few seconds until the chat button fully reloads.
    3. You can access the iframe data, here there are the steps.

    Select the iframe element.

    Access the iframe’s contentWindow.document or contentDocument.

    Find the .chat-button inside the iframe.

    Click on it.

    window.onload = function() {
        let iframe = document.querySelector("iframe");
    
        if (iframe) {
            iframe.onload = function() {
                let iframeDoc = iframe.contentDocument || iframe.contentWindow.document;
    
                if (iframeDoc) {
                    // Check for chat button every 500ms
                    let checkButton = setInterval(function() {
                        let chatButton = iframeDoc.querySelector(".chat-button");
    
                        if (chatButton) {
                            chatButton.click(); // Click the button
                            console.log("Chat button clicked!");
                            clearInterval(checkButton); // Stop checking once clicked
                        }
                    }, 500); // Adjust the interval time if needed
                }
            };
        } else {
            console.log("Iframe not found.");
        }
    };