Question

In Magento 2 I need to invoke some JS tracking when the following things happen:

  • customer logs into site
  • customer registers account
  • newsletter subscribe success
  • customer updates account details
  • order success

Apart from order success which has an actual page to trigger the JavaScript, I'm not sure on the best way to track the other events seeing as their success seems to be fully handled by PHP only.

Regarding the login/register requirement I have seen that there's a JS handler in module-customer/view/frontend/web/js/action/login.js which has this:

action.registerLoginCallback = function(callback) {
        callbacks.push(callback);
    };

But I'm not sure how this can be hooked into in my module. Are there any resources that could help here? I'm just looking for suggestions on the best practice way to approach this.

Was it helpful?

Solution

I ended up having to use cookies due to how slow the local storage was to load so I have answered my question with this blog post: https://adammoss.co.uk/magentofox/private-data-tracking-in-magento-2/

OTHER TIPS

I have a suggestion.

Take a look: vendor/magento/module-customer/view/frontend/layout/default.xml

<block name="customer.customer.data"
               class="Magento\Customer\Block\CustomerData"
               template="Magento_Customer::js/customer-data.phtml"/>

Magento will load js/customer-data.phtml on every page. The js file: js/customer-data.js is also loaded.

We need add our custom js via phtml on every page with after.body.start

app/code/Vendor/Tracking/view/frontend/layout/default.xml

<?xml version="1.0"?>

<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceContainer name="after.body.start">
            <block class="Vendor\Tracking\Block\Js"
                   name="tracking" as="tracking" template="js.phtml"/>
        </referenceContainer>
    </body>
</page>

Create the our tracking js and put it in js.phtml template.

We can check the data with: $(document).on('submit', function() {}); and $(document).on('ajaxComplete', function (event, xhr, settings) {}). See more: vendor/magento/module-customer/view/frontend/web/js/customer‌​-data.js.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top