How can I trigger my custom statistics script on every page "load"?

Knowing that Discourse is a SPA and having looked at some docs around this topic I am still not sure how to achieve this:

  • we include a custom js library in the footer that interfaces with our statistics solution
  • we want to enrich the stats by triggering custom events on every “page load”, e.g whenever the user navigates to a “new” page

Pseudo code:

window.statistic = window.statistic || [];
    action: "page.ready",
    data: {
        page: {
            path: "/c/new-to-this-forum-get-started-here/20/l/new",
            country: "WW",
            language: "en",
}, user: {
            country: "DE",
            loginStatus: "logged_in"
} });

How and where in my custom theme do I need to place the code to achieve this?

Thanks :slight_smile:

1 Like

You’ll likely want to use onPageChange from our plugin API.

In a theme, you’d want to add something like this to javascripts/discourse/api-initializers/your-initializer.js

import { withPluginApi } from "discourse/lib/plugin-api";

export default {
  name: "custom-script-name",

  initialize() {
    withPluginApi("0.8.36", (api) => {
      api.onPageChange(() => {
        // script you want to fire on page change here

Thank you! That did the trick.

Do you also happen to know how I can get the UI language from the user’s settings?

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.