Skip to content

Instantly share code, notes, and snippets.

@vasilii-b
Last active March 13, 2023 12:28
Show Gist options
  • Save vasilii-b/08ab84b61fa7826dc0496ab1bf3f0676 to your computer and use it in GitHub Desktop.
Save vasilii-b/08ab84b61fa7826dc0496ab1bf3f0676 to your computer and use it in GitHub Desktop.
Collect Klevu results from JS templating for later usage (send to GA4 for example)

Magepal GA4 <> Klevu Search using JS Templating

The files mentioned in the gist are supposed to be added under a custom theme (app/design/frontend/<vendor>/theme) inside the folder Klevu_Search.

Alternatively, the same could be achieved by having the files (layouts, templates) inside a custom module.

<!-- file: layout/klevu_category_index.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">
<update handle="magepal_ga4_klevu_collect_data"/>
</page>
<!-- file: templates/magepal-collect-products.phtml -->
<script type="text/javascript">
klevu.coreEvent.build({
name: "magepalGa4Klevu",
fire: function () {
if (
klevu.getGlobalSetting("flags.setRemoteConfigLanding.build", false) ||
klevu.getGlobalSetting("flags.setRemoteConfigCatnav.build", false)
) {
return true;
}
return false;
},
maxCount: 150,
delay: 100
});
klevu.coreEvent.attach("magepalGa4Klevu", {
name: "attachMagepalGa4KlevDataCollecting",
fire: function () {
const area = klevu.search.catnav || klevu.search.landing;
if (!area) {
return;
}
area.getScope().chains.response.success.addAfter("processQuery", {
name: "grabProductsFromQuery",
fire: function (data, scope) {
// the event will fire on the initial Klevu products load on the page
// as well as on future product attachments to the page (infinite scrolling e.g.)
console.debug(data.response.data.queryResults);
console.table(data.response.data.queryResults[0].records);
}
});
}
});
</script>
<!-- file: layout/magepal_ga4_klevu_collect_data.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="before.body.end">
<block name="magepal_ga4_gollect_klevu_results" template="Klevu_Search::magepal-collect-products.phtml"/>
</referenceContainer>
</body>
</page>
<!-- file: layout/search_index_index.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">
<update handle="magepal_ga4_klevu_collect_data"/>
</page>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment