user3605780
user3605780

Reputation: 7072

Set gtag utm parameters manually using javascript

For better tracking cross domain iframes I want to manually set the utm parameters for gtag of Google Analytics.

I cannot change the url that it adds the utm_source={source} etc.

My iframes are loaded like:

<iframe src="https://example.com/?pagetest=a&source=source_page"></iframe>

Then on the serverside I will extract these parameters so if another parent site puts i.e. referer_source instead of just source I can change this so in the javascript all variables will be the same.

I found this thread, however it's not working for me. This is the script code in the header:

     <script async src="https://www.googletagmanager.com/gtag/js?id={id}"></script>
    <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());
        gtag('config', '{id}',{
        'page_title':'title',
        'page_referrer':'{ source }',
        'page_location':'/current_page',
        'page_path':'/current_page',
        });

        // Sends an event that passes 'age' as a parameter.
        gtag('event', 'page_view', {'pagetest': 'a'});
    </script>

I still see the parent domain of the iframe as the referral, and at events tab I only see

event category: general ; event action : pagetest; events: 100%

I would like to have the analytics for totals on the page, and then be able to break down on pagetest a and pagetest b in example.

How can I set all these points in javascript?

Upvotes: 0

Views: 1674

Answers (1)

Open SEO
Open SEO

Reputation: 1712

You could try something like this, tell me how far it matches your use case:

    <script async src="https://www.googletagmanager.com/gtag/js?id={id}"></script>
<script>
    window.dataLayer = window.dataLayer || [];

    function gtag() {
        dataLayer.push(arguments);
    }
    // set everything once for every susbsequent hits
    // add source information to LOCATION throught utm_referrer
    // clear the referrer value to prevent interfering with the value you're adding through utm_referrer
    gtag('set', {
        'page_location': '/current_page' + '?utm_referrer=' + encodeURIComponent(source),
        'page_referrer': null,
        'page_path': '/current_page'
    });
    gtag('js', new Date());
    gtag('config', '{id}', {
        'page_title': 'initial page title'
    });

    // Send another page view 
    gtag('event', 'page_view', {
        'page_path': '/virtual_page_path_value',
        'page_title': 'title for virtual page view'
    });
</script>

Upvotes: 1

Related Questions