Login Event Listener

AI-generated summary

The discussion revolves around creating a login event listener in vanilla JavaScript for a Discourse forum. aliparsifar wants to run a JavaScript function every time a user logs in, and is looking for a DOM event to listen for. Johani provides a solution using a theme component, which listens for the modal:body-shown event and adds an event listener to the #login-button element. The code can be customized in the clickCallback function to perform the desired action when the user clicks the login button.

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

Thanks so much for the response, Joe!