Magento 2 - How to check customer is logged in or not using cookie?

by Sanjay Gohil   Last Updated June 25, 2019 07:09 AM

I want to achieve below functionality.

When user visit my website I want to setup cookie for example 30 second, After 30 second if user is not register then ask him/her for registration. It is just like registration reminder.

Can anyone help me how can I Implement this functionality.

Any help would be appreciate.



Answers 2


Use below code for check user login or no

protected $_session;
protected $_context;
protected $objectManager;

public function __construct(
    \Magento\Customer\Model\Session $session,
    \Magento\Framework\View\Element\Template\Context $context
) {     
    parent::__construct($context);
    $this->objectManager = $context->getObjectManager();
} 


public function isCustomerLoggedIn()
{
    $session = $this->objectManager->get('Magento\Customer\Model\Session');    
    if($session->isLoggedIn()) {
       $status = "Customer logged in";
    }else{
        $status = "Not customer logged in";
    }
    return $status;
}

Also you can use check user login or not using cookies

define(['Magento_Customer/js/model/customer'], 
    function(customer) {
        return Component.extend({
            someMethod: function () {
                if (customer.isLoggedIn()) {
                   //do smth
                } else {
                   //do smth
                }
            },
        });
    }
);

Get Reference

Shorabh
Shorabh
June 25, 2019 06:41 AM

You can check customer is logged in or not using below code in your custom module js

require(['jquery', 'Magento_Customer/js/model/customer'],function($, customer){
    jQuery(document).ready(function(){
        var timer = setTimeout(function(){        
            if(customer.isLoggedIn()){
                //Customer logged in
            } else {
                //Customer not logged in
            }
            clearTimeout(timer);
        },30000);
    });
});
Ranganathan
Ranganathan
June 25, 2019 06:59 AM

Related Questions


Registration is broken after switch to HTTPS

Updated December 04, 2017 14:09 PM