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 %}
---
## {{ 'customer.login.guest_title' | t }}
{% form 'guest_login' %}
{% if form.posted_successfully? %}
{% endif %}
{% endform %}
{% endif %}
{% 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
Add this to your Body tag
On GTM you could do something like this
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