add custom script when login successfully

add custom script when login successfully

Patrick_Lin
Shopify Partner
1 0 0

I want to trigger a custom script about GTM code when the user login successfully. But the page will be redirected to other pages when the user clicks the login button. Does anyone know how to fix it?

 

    {% if shop.checkout.guest_login %}
      <div class="text-center">
        <hr class="hr--invisible">
        <h2>{{ 'customer.login.guest_title' | t }}</h2>

        {% form 'guest_login' %}
                  {% if form.posted_successfully? %}
            <span data-success class="hide"></span>
        <script>
console.log('Login successfully ') //doesn't work
   </script>
          {% endif %}
          <input type="submit" class="btn btn--primary btn--form" value="{{ 'customer.login.guest_continue' | t }}">
        {% endform %}
      </div>
    {% endif %}

 

Reply 1 (1)

Michel_Arteta
Shopify Partner
33 2 35

{% if form.posted_successfully? %} will not work. I tried to assign form.posted_successfully? to a variable and grab its value couldn't make it work but you can try another alternative which is to pass a parameter to the success URL and set a trigger in GTM for all pages that checks for that paramter

 

Add this to your Login Form 

 

<input type="hidden" name="checkout_url" value="/account?login_success=true"> 

 

 

Add this to your Body tag

<body data-customer-id="{{customer.id}}">

 

On GTM you could do something like this

 Screen Shot 2022-08-30 at 2.45.41 PM.png

or in your code you could do something like this: 

 

 

const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString);
const loginSuccess = urlParams.get('login_success');
const customer = document.querySelector('[data-customer-id]');
const customerId = customer.getAttribute('data-customer-id');

if (loginSuccess) {
  dataLayer.push({
    event: 'login',
    user_id: customerId,
  });
  console.log('login');
  // Remove params from URL to avoid multiple events to fire. 
  window.history.pushState({}, null, window.location.href.split('?')[0]);
} 

 

 

Let me know if it works or if someone made the {% if form.posted_successfully? %} works