我成功获取了分类页面和主题页面的分类 ID,
但当我进入常见问题(FAQ)或其他页面时,仍会显示上一页的分类 ID。
该如何排除这种情况?
以下是我的代码,它目前可以运行,但我对 JavaScript 并不熟悉。
<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>
我可能在变量处理上出了错,或者需要获取其他类型页面的控制器。