Get Category Name using JS

Hi, maybe someone can help.
I need to get the category name of the current page.
I need to get this in a JS script that I can add to Footer or Body.
I’ve tried a couple of solutions, but I can’t get it to be stable and given the user’s page transitions.
I plan to pass the resulting category name as an Event in Google Analytics to count visits for each category.

There might be a way to consistently do it across both topics and category pages, but I’ve gotten the category ID in two different ways… one for category pages:

<script type="text/discourse-plugin" version="0.8">
const container = Discourse.__container__;
const controller = container.lookup('controller:navigation/category');

api.onPageChange((url, title) => {
  console.log(controller.get("category.id"));
});
</script>

and a similar way for topic pages:

<script type="text/discourse-plugin" version="0.8">
const container = Discourse.__container__;
const controller = container.lookup('controller:topic');

api.onPageChange((url, title) => {
  console.log(controller.get("model.category_id"));
});
</script>

In the category page example you can alternatively use category.name or category.slug but with the topic model only the category_id is available so you’d have to do a little more work there to get the name. ID might be a better path anyway because it’s consistent even if the category name or slug changes.

9 Likes

I was able to get the Category ID for the Category and Topic pages,
But when I go to the FAQ or another page, the Category ID is also displayed, from the previous page.
How can I exclude this?

Here is my code, it works, I do not know JS in general.

<script type="text/discourse-plugin" version="0.8">
const container = Discourse.__container__;

api.onPageChange((url, title) => {
    const topic = container.lookup('controller:topic');
    const topic_cat_id = topic.get("model.category_id");
    if(typeof topic_cat_id !== "undefined")
    {
        gtag('event', 'Categories Views Analytics', {
            'event_category': 'Topic Page',
            'event_label': topic_cat_id,
        });
        console.log("Topic " + topic_cat_id);
    } else {
        const category = container.lookup('controller:navigation/category');
        const category_cat_id = category.get("category.id");  
        
        if(typeof category_cat_id !== "undefined") 
        {
            gtag('event', 'Categories Views Analytics', {
                'event_category': 'Category Page',
                'event_label': category_cat_id,
            });  
            console.log("Category " + category_cat_id);
        } else {
            gtag('event', 'Categories Views Analytics', {
                'event_category': 'Other Page',
                'event_label': 'Other Page'
            });              
            console.log("Other");
        }
    }
});
</script>

I must have messed up something in the variables or need to get a controller of a different type of page.

1 Like