1

I have a GTM script for login in Magento_Customer/templates/account/dashboard/info.phtml

<script>
dataLayer.push({
    'events':{
        'event':'login',
        'category':'login',
        'action':'login',
        'label': <?php echo "'" . $block->getCustomer()->getId() . "'" ?>

    },
    'user':{
        'visitorLoginState':'logged in'
    }


 });
</script>

I want this script to run just one time, when a user is logged in. Now if a refresh the browser the script run again.

Does anyone know how can i run this script just one time?

A know i can use registry, but i am in a phtml.

Thank you!

0

You can use customer session variable.

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customerSession = $objectManager->create('Magento\Customer\Model\Session');
if(!$customerSession->getIsScriptRun()){
     ....Your Code....
     $customerSession->setIsScriptRun(true);
}

Now to clear customer session after a customer logs out, You need to create an observer
Create a file etc/frontend/events.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="controller_action_predispatch_customer_account_logout"> <!-- use one of the events above -->
        <observer name="[namespace]_[module]" instance="[Namespace]\[Module]\Observer\Logout" />
    </event>
</config>

Create observer file [Namespace]/[Module]/Observer/Logout.php and add below code.

<?php 
namespace [Namespace]\[Module]\Observer;

class Logout implements \Magento\Framework\Event\ObserverInterface 
{
    public function execute(\Magento\Framework\Event\Observer $observer)
    {
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $customerSession = $objectManager->create('Magento\Customer\Model\Session');
        $customerSession->unsIsScriptRun();
    }
}
  • what this ->getIsScriptRun()) means? – Alin Lupoiu Feb 8 '17 at 13:22
  • It is a session variable. First time it will not be set and will allow the script to run. then we have set value for the session variable using $customerSession->setIsScriptRun(true); so the condition if(!$customerSession->getIsScriptRun()) will not be true and the script will not run again. – Jaimin Sutariya Feb 8 '17 at 13:26
  • it works for the firs time. but if a try to login with another user the script it's not run again. can i do something to run when i logged in with another user? – Alin Lupoiu Feb 8 '17 at 13:35
  • You mean when you logged out from one user and logged in with another, at that time the script is not working? – Jaimin Sutariya Feb 8 '17 at 15:49
  • yes. it's not working – Alin Lupoiu Feb 8 '17 at 15:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.