docusaurus 2: run custom script for every page

Viewed 900

Is it possible to run some custom script for every page?

E.g., I want to run alert(1); on every page. How can I do that without the sizzling of any components?

I know it can be done by creating jsx component and using it in every .mdx file (but every doc then should be a .mdx file). So it's not the thing I'm looking for.

1 Answers

Docusaurus 2 user here!

Docusaurus is Server-Side Rendered and then hydrated to function as a Single Page Application. Without knowing more about what you want to achieve, I can only try to give you a general advice.

One way of achieving this is to create your own plugin, it gives you access to the execution context, such as router events.

I currently use this for analytics reporting when the user changes page. It's not yet documented, but there's a good example in the Docusaurus 2 repository in the docusaurus-plugin-google-analytics package.

Here's a fragment of what I use, this only executes when a new page is loaded, which fits my use case perfectly. There may be another lifecycle hook called when the page is hydrated that I haven't found yet.

analytics-module.js

import ExecutionEnvironment from "@docusaurus/ExecutionEnvironment";

export default (function () {
  if (!ExecutionEnvironment.canUseDOM) {
    return null;
  }

  return {
    onRouteUpdate({ location }) {
      _paq.push(["setCustomUrl", location.pathname]);
      _paq.push(["setDocumentTitle", document.title]);
      _paq.push(["trackPageView"]);
    },
  };
})();

Related