4

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.

Maksim Nesterenko
  • 5,661
  • 11
  • 57
  • 91

1 Answers1

5

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"]);
    },
  };
})();

Marcus Cemes
  • 692
  • 1
  • 8
  • 18
  • cool , how do we integrate it in Docusaurus config or which is the place to include the module file ? – Bhupendra Jul 07 '22 at 11:52
  • 1. define client module https://docusaurus.io/docs/api/docusaurus-config#clientModules 2. I used `myClientModule.ts` at the end of the page https://docusaurus.io/docs/advanced/client#client-modules – crazyx13th Aug 02 '22 at 06:21