1

I have this piece of code as a javascript custom variable in the Google Tag Manager. I would like to get breadcrumbs content.

This part of the code works well. But some pages do not have breadcrumbs, for these pages I use title instead. Because I do not want to have undefined in Google Analytics dimension.

So far everything is ok as a separate part of code. But If I try to check whether breadcrumbs variable is undefined (there is not breadcrumbs class on the page and breadcrumbs variable is based on the content of breadcrumbs class), I will not be able to check this. "IF" statement just does not work.

I have tried multiple approaches to check variable (typeof, check value ...) but nothing works for me.

Can you help me?

function() {
    var breadcrumbs = document.getElementsByClassName('breadcrumbs').item(0).innerText;


    if (typeof breadcrumbs === 'undefined'){
        breadcrumbs = {{JS - Title}}.substring(0, breadcrumbs.indexOf(' |'));
    }else{
        breadcrumbs = breadcrumbs.replace(/(?:\r\n|\r|\n)/g, '| '); 
    }

    return breadcrumbs;
}
0

1 Answer 1

0

The problem with your code, is that breadcrumb variable is not evaluated to undefined, but throws an error, when no element with breadcrumbs class is present. However, GTM catches this error, and returns undefined as a result of the whole function (variable). So, your if statement is actually not evaluated at all.

If you run code directly from console, where no relevant element is present, you get an error:

var breadcrumbs = document.getElementsByClassName('breadcrumbs').item(0).innerText;

VM29:1 Uncaught TypeError: Cannot read property 'innerText' of null at :1:73

To overcome this, you should break down the steps to get the relevant element, and place the IF statement accordingly. E.g.

function() {
    //get all breadcrumb elements
    var breadcrumbElements = document.getElementsByClassName('breadcrumbs');

    //check, if any elements are found
    //if not, return title instead
    if (breadcrumbElements.length === 0){
        return {{JS - Title}};
    } 

    //breadcrumb found
    //return data from breadcrumb
    return breadcrumbElements.item(0).innerText.replace(/(?:\r\n|\r|\n)/g, '| '); 

}

Please note, that I was not able to figure out, why you refer to breadcrumbs variable, where you expect it to be undefined: .substring(0, breadcrumbs.indexOf(' |')) So I've skipped this part, which you might need to adjust, to get the expected value from {{JS - title}}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.