Help with Inserting Google Script (gtag.js) with Dynamic Data via Server Connect in Wappler

Hi everyone,

I’m facing an issue in a Wappler project where I need to insert a Google Tag (gtag.js) script and pass a dynamic value, specifically the conversion_id, which is fetched directly from the database via Server Connect.

The goal is that, when the page loads, the Google Tag script should be dynamically populated with the conversion_id, which is returned from my Server Connect.

What I’ve Tried So Far:

  1. JavaScript function to retrieve the data:

• I attempted to create a function to fetch the data using dmx.app.data.sc_cart.data.query_gads.conversion_id, but I keep getting errors that sc_cart is not defined or that the data is not loaded.

• I also tried using the onsuccess attribute in the Server Connect to trigger the function, but the dynamic data wasn’t available when the function was called.

  1. Watcher to check when the data is loaded:

• I tried an approach using dmx.app.data.sc_cart.load().then() to ensure the data was available before injecting the script, but I still couldn’t get it to work.

  1. Different methods of structuring the script:

• I experimented with several ways to inject the conversion_id directly into the script via JavaScript, but either the script wouldn’t load or the data wasn’t being populated.

What I Need:

I need a reliable and efficient way to insert the Google Tag script with the dynamic conversion_id as soon as it is loaded by Server Connect. The value of conversion_id comes from sc_cart.data.query_gads.conversion_id.

The expected code should look something like this:

<script async src="https://www.googletagmanager.com/gtag/js?id={{ sc_cart.data.query_gads.conversion_id }}"></script>
<script>
    window.dataLayer = window.dataLayer || [];
    function gtag(){ dataLayer.push(arguments); }
    gtag('js', new Date());
    gtag('config', '{{ sc_cart.data.query_gads.conversion_id }}');
</script>

However, I’m struggling to ensure that the dynamic value is correctly loaded.

Has anyone faced this issue or can offer any suggestions on how to resolve this integration problem with Wappler?

I’ve already tried everything mentioned in this post, but I haven’t had any success:

Google Global Site Tag (gtag.js) tracking code insertion issue](Google Global Site Tag (gtag.js) tracking code insertion issue

I’d appreciate any help!

Note: My page is a content page, so the script will be placed in the body and not in the head. My project is Node.js

Can you just load the entire script from the db?

I load the tag (or other scripts) for tenants on the layout using Server Side data. The server side workflow retrieves the scripts

Screenshot 2024-09-26 at 1.03.50 PM

and then I display using

<%-_('snippets.head_start')%> in the head or body of the layout.

1 Like

Yes, I tried this alternative. I also saw your post talking about it. But whenever I try to use the <%-_('myShortCode')%> my code breaks and I get a 500 error.

I tried using dmx.parse but without success so far.

@Teodor Can help with this?

Hi,
Configure your server action as server side data on your content/layout page and don't use server connect.
Then you can use the server side binding to place the conversion_id or the complete script on the page, server side, before the page renders.

Eg:

<span class="ms-xl-0 ms-2"><%=_('varMeta.settings',locals)%></span>

Here varMeta is just a variable in the server action.

1 Like
  1. Use dmx.parse to evaluate a Wappler expression (remember, you can test this in the browser console by calling the dmx.parse function there)
gtag('config', dmx.parse('sc_cart.data.query_gads.conversion_id'));
// Might have to be prefixed with "content." if the Server Connect is not on the main layout
gtag('config', dmx.parse('content.sc_cart.data.query_gads.conversion_id'));
  1. Only load Google's script after the Server Connect has successfully executed. You have to wrap inside a function to be called after the Server Connect loads:
<script>
function runGoogle() {
    window.dataLayer = window.dataLayer || [];
    function gtag(){ dataLayer.push(arguments); }
    gtag('js', new Date());
    gtag('config', dmx.parse('content.sc_cart.data.query_gads.conversion_id'));
}
</script>
  1. On your Server Connect, create Dynamic Event "On Success" (paraphrased) and insert a Flow with a Run JavaScript step, it needs to call "runGoogle" function
1 Like

Thank you very much for your help, I believe I'm on the right track now!

What I'm doing is: (check if it's correct)

<dmx-serverconnect id="sc_cart" url="/api/cart/cart" dmx-param:code="query.code" dmx-on:success="run({runJS:{name:'GoogleTag',outputType:'text',function:'runGoogle'}})"></dmx-serverconnect>

<script>
    function runGoogle() {
        window.dataLayer = window.dataLayer || [];
        function gtag(){ dataLayer.push(arguments); }
        gtag('js', new Date());
        var conversionId = dmx.parse('content.sc_cart.data.query_gads.conversion_id');
        gtag('config', conversionId);

        console.log("Google Tag Manager loaded success Conversion ID:", conversionId);
    }
</script>

I can get the conversion_Id correctly

image

but it doesn't render when the page loads.

Do I need to do anything else to make it work? @Apple

I think everything looks good! Maybe that Tag Analyser is looking for a literal ID in the source-code, but you're setting the ID dynamically so it can't find it. It also says there's a (browser) extension available, so maybe that can find the tag

You're welcome!

P.S.: The other alternative is server-side binding, what @ mebeingken was doing, but it requires you to think a bit differently (unfortunately, I don't have time to explain)

1 Like

Got it @Apple

I tried to debug there too, but unfortunately it can't find any active tags, so the Google tag can't perform its function of marking events.

It's as if the tag is there, but it's not being rendered by JavaScript.

I tried this here, but it works very badly, the first time the page loads the script doesn't activate, the second time it activates, the third time it doesn't activate and so on.

div id="conversionId" dmx-bind:data-script="sc_cart.data.googlescript" style="display:none;"></div>

<script>
    function loadDynamicScript() {
        var scriptContent = document.getElementById('conversionId').getAttribute('data-script');

        if (scriptContent) {
            var tempDiv = document.createElement('div');
            tempDiv.innerHTML = scriptContent;

            var scriptTags = tempDiv.getElementsByTagName('script');
            for (var i = 0; i < scriptTags.length; i++) {
                var scriptElement = document.createElement('script');
                scriptElement.type = 'text/javascript';

                if (scriptTags[i].src) {
                    scriptElement.src = scriptTags[i].src;
                } else {
                    scriptElement.text = scriptTags[i].innerHTML;
                }

                document.body.appendChild(scriptElement);
            }

            console.log("Scripts add in DOM.");
        } else {
            console.error("Not found.");
        }
    }

    window.onload = loadDynamicScript;
</script>

I don't know what else to do to make this work, it seems so simple but at the same time so complex.

You can only load that script after the Server Connect sc_cart loads (Dynamic Event On Success)
You're loading on page load:

window.onload = loadDynamicScript;

You have to comment/remove that line

P.S.: I don't know anything about Google Tags

1 Like

Perfect

It worked here, with some adaptations, but you gave me the right path.

Thanks again.

1 Like