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

AI-generated summary

nodomain wants to trigger a custom statistics script on every page “load” in a Discourse SPA. They have a custom js library that interfaces with their statistics solution and want to enrich the stats by triggering custom events on every “page load”.

awesomerobot recommends using onPageChange from the plugin API and provides an example of how to implement it in a theme’s javascripts/discourse/api-initializers/your-initializer.js.

nodomain confirms that this solution works and asks for additional help on how to get the UI language from the user’s settings.

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 || [];
window.statistic.push({
    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:

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?