Login Event Listener

Hi,

I’m trying to track user logins on our client’s forum. Basically, I’d like to create an event listener (in vanilla JS) that runs a JavaScript function every time a user logs in to the forum.

Is there a DOM event that I can listen for?

I’m trying to do this in Google Tag Manager.

Thanks.

You can use something like this in the common > header tab of a theme component.

<script type="text/discourse-plugin" version="0.8">
  const user = api.getCurrentUser();

  // user is already logged in, bail
  if (user) {
    return;
  }

  // do your work here...
  const clickCallback = (clickEvent) => {
    console.log(clickEvent);
    alert("user is logging in");
    // ..
    // ..
  };

  api.onAppEvent("modal:body-shown", (event) => {
    const loginButton = document.querySelector("#login-button");

    if (loginButton) {
      loginButton.addEventListener("click", clickCallback, { once: true });
    }
  });
</script>

Add whatever code you need in the clickCallback function, and it will fire when the user clicks on the Login button inside the modal. That id is currently missing on mobile, but that will be fixed when this is merged

3 Likes

Thanks so much for the response, Joe!

1 Like