简体   繁体   中英

gtag Linker not working on JS form.submit()

I used correct google tagging to enable cross-domain tracking. When the form is submitted by clicking on submit button the ?ga=... will be added to the destination URL but, it won't be added if I trigger the submit event by JS.

Code is as follows:

<head>
    <script>
        //All other common JS code exist
        gtag('set', 'linker', {
            'domains': ['example.com'],
            'decorate_forms': true
        });
        gtag('config', 'UA-...');
    </script>
</head>
<body>
    <form method="POST" action="https://example.com/a/b">
        <button type="submit">Submit</button>
    </form>
    <button id="bt">Click to submit form using JS</button> 
    <script>
        $(document).on('click', '#bt', function(e){
            $('form').submit();
        });
    </script>
</body>

If I add submit button to form and click on it directly the destination will be something like https://example.com/a/b?_ga=... . However, when I submit the form via JS, destination URL is just like the form action without GA appendix.

I have to note that I'm using gtag and not GTM.

It can be solved in two different ways:

Method 1 We can change the submit trigger to a click trigger on the submit button. Don't know why but, it solves the issue :)

$(document).on('click', '#bt', function(e){
    $('form button[type="submit"]').trigger('click');
});

Method 2 We can handle anything we want in the submit event instead of the click event on some other button other than submit.

$(document).on('submit', 'form', function(e){
    //Do your stuff and handle the event
    return true;
});

Although the problem seems to be solved, the main question still exists and it seems it is pointing to a potential bug for gtag or jquery form.submit() . Therefore, if you can provide any solution or answer for the open question, go ahead and publish your post and I'll make your answer as a correct one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM