Learn business growth with Google Analytics 4 Forums Google Analytics 4 Recording the Visibility of a Shadow DOM Element in the Browser Reply To: Recording the Visibility of a Shadow DOM Element in the Browser

  • Bailey

    18 April 2023 at 3:38 am

    Yes, you can set up a dataLayer push to fire an event when the element shows itself using a custom HTML tag in GTM.

    You would use a MutationObserver with GTM. MutationObserver provides developers a way to react to changes in a DOM. It is designed to react to changes in the structure of a document’s tree, like the addition or removal of elements, changes in element’s attributes, and more.

    You need to write a custom bit of JavaScript which you run on the page as a Custom HTML tag. This script creates a new MutationObserver which then watches the element (which you can target as you have done via the shadowRoot method when it’s available). If the element is found, the MutationObserver fires, sending an event to the dataLayer.

    Here is a sample JavaScript you might use:

    (function() {
    // Ensure the element with ‘c-cp-login’ ID exists on the page
    var targetNode = document.querySelector(‘c-cp-login’);
    if (targetNode) {
    // Configuration of the observer:
    var config = {
    attributes: true,
    childList: true,
    subtree: true
    // Callback function to execute when mutations are observed:
    var callback = function(mutationsList, observer) {
    // Look through all mutations that just occured:
    for (var mutation of mutationsList) {
    // If a childNode was added (or removed), use querySelector to see if your element now exists:
    if (mutation.type === ‘childList’) {
    var errorElement = targetNode.shadowRoot.querySelector(‘.slds-form-element.cp-padding-left-right.cp-error_text’);
    if (errorElement) {
    // If your element exists, push to dataLayer and stop observing:
    event: ‘elementShown’,
    element: ‘YOUR_ELEMENT’
    // Create an observer instance linked to the callback function:
    var observer = new MutationObserver(callback);
    // Start observing the target node for configured mutations:
    observer.observe(targetNode, config);

    The ‘elementShown’ event can be then used within GTM to trigger your GA4 tag.

    Bear in mind that MutationObservers should be used sparingly and detached as soon as they are not required anymore, which is why in the code above, we disconnect the observer as soon as it detects the desired element. This is due to the potential performance impact they can have if there are a huge number of DOM changes.