jQuery, Magento2

How to use Cookie in Magento2?

use cookie in magento2

In this blog We will discuss the topic of how to use Cookie in Magento2? Cookies are the most used technology for storing data on the client side.

You can add below code in your phtml file or convert that code for js file also.

Set cookie : To both create and retrieve a cookie, jquery.cookie uses the same method, cookie(), but with a different number of parameters.

To create a cookie you need to pass in two required parameters, the name and value of the cookie, respectively. You can pass a third, optional, parameter that is an object literal containing some additional options.

These options are pathdomainexpires, and secure.

<script type="text/javascript">
    require([
        'jquery',
        'jquery/jquery.cookie'
    ], function ($) {
        $(document).ready(function () {

            var date = new Date();
            var minutes = 60;
            date.setTime(date.getTime() + (minutes * 60 * 1000));
            $.cookie('foo', '', {path: '/', expires: -1}); // Expire Cookie
            $.cookie('foo', 'bar', {expires: date}); // Set Cookie Expiry Time
            $.cookie('foo', 'setvalue'); // Set Cookie Value
        }
    });
</script>

How to Get cookie?

<script type="text/javascript">
    require([
        'jquery',
        'jquery/jquery.cookie'
    ], function ($) {
        $(document).ready(function () {
            var check_cookie = $.cookie('foo'); // Get Cookie Value
        }
    });
</script>

How to add condition if cookie set or not?

<script type="text/javascript">
    require([
        'jquery',
        'jquery/jquery.cookie'
    ], function ($) {
        $(document).ready(function () {
            var check_cookie = $.cookie('foo'); // Get Cookie Value
            if($.cookie('check_cookie')) 
	            { 
	            	console.log('Cookies Set');
	            }
            else
	            {
	               	console.log('Cookies Set'); 
	            }
        }
    });
</script>

View, Edit, And Delete Cookies With Chrome.

DevDocs Home

🙂 Happy Coding. Keep Liking & Sharing 💻

Tagged , ,