Question

In GTM (Google Tag Manager), you can have custom JavaScript macros, which are anonymous functions that return something use by a tag or a rule.

Each of my macros are using try/catch so we can easily surface any implementation error (raising a dataLayer event which is catch by a UA tag)

But here’s something odd… if I uncomment the try/catch, GTM stubbornly refuses to use it and doesn’t give any error… but goes in ever saving mode (i.e. browser keeps waiting for something). I know this code works when I run it in the debug console… and I have other macros with the same try/catch technique... Any thoughts?

function () {
    /*try {*/
        var v = '';
        // HTML5 video
        if(document.getElementsByTagName('video').length) v += 'video,';
        // Youtube video
        var i = document.getElementsByTagName('iframe');
        for(x = 0; x < i.length; x++)
            if(/youtube.com\/embed/.test(i[x].src)) {
                v += 'youtube,';
                break;
            }
            // Limelight video
        if(document.getElementsByClassName('LimelightEmbeddedPlayer')) v += 'limelight,';
        return v.length ? v.slice(0, -1) : v;
    /*} catch(e) {
        dataLayer.push({
            'event': 'error',
            'action': 'GTM',
            'label': '713-Video Type:' + e.message
        });
    }*/
}
Was it helpful?

Solution

Your issue broken JavaScript syntax. For-loop needs braces around it and if possible, use them always with e.g. ifs. I recommend using JSHint to test your code for syntax errors at least every now and then.

I modified your source a bit, try this:

function () {
    /*try {*/
        var v = '';
        // HTML5 video
        if(document.getElementsByTagName('video').length) {
            v += 'video,';
        }
        // Youtube video
        var i = document.getElementsByTagName('iframe');
        for(var x = 0, l = i.length; x < l; x++) {
            if(/youtube\.com\/embed/.test(i[x].src) && !/youtube/.test(v)) {
                v += 'youtube,';
            }
            // Limelight video
        }
        if(document.getElementsByClassName('LimelightEmbeddedPlayer')) {
            v += 'limelight,';
        }
        return v.length ? v.slice(0, -1) : v;
    /*} catch(e) {
        dataLayer.push({
            'event': 'error',
            'action': 'GTM',
            'label': '713-Video Type:' + e.message
        });
    }*/
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top