This article is basically follow up on previous one.

There I talked about popup/sliding panel handling, but if you want to improve that with cookies usage (for example, to auto-load popup just once per session or similar …) here you can find some useful tips.

In Magento 2 you can achieve that with PHP or JavaScript (jQuery, mage/cookies, js-cookie, …)

From what I have experienced, the best way is with the js-cookie plugin (inheritor of jQuery Cookies which is “retired” from 2015).

Why not PHP?
PHP approach cannot be implemented in custom block from Magento backend, and JavaScript can through require.js.

Why not jQuery Cookies plugin?
As I mentioned, it’s retired from 2015, and people who worked on it continued the job on js-cookie plugin. Beside that, cookie retrieving not working anymore (at least for me).

So which one?
That plugin can be found here – https://github.com/js-cookie/js-cookie

Only file that you need is – https://github.com/js-cookie/js-cookie/blob/master/src/js.cookie.js

So, steps for the implementation are:

1. Place js.cookie.js in \lib\web
2. Run Static Content Deploy command – php bin/magento setup:static-content:deploy
3. Go to place where you want to use js-cookie and call it.

    require(
        [
            'jquery',
            'js.cookie'
        ],
        function($, Cookies) { …. }

Usage:
Set cookie – Cookies.set(‘name’, ‘value’, { expires: 30 }); // expires in 30 days
Get cookie – Cookies.get(‘name’); //returns value
Remove cookie – Cookies.remove(‘name’);

Complete documentation can be found here
https://github.com/js-cookie/js-cookie

Updated code from the previous article now looks:

<script type="text/javascript">
    require(
        [
            'jquery',
            'Magento_Ui/js/modal/modal',
            'js.cookie'
        ],
        function($, modal, Cookie){
            var options = {
                type: 'popup', // there is also a slide type. By default sliding from the right.
                responsive: true,
                innerScroll: true,
                buttons: [{
                    text: $.mage.__('Close'),
                    class: '',
                    click: function () {
                        this.closeModal();
                    }
                }]
            };
 
            var popup = modal(options, $('#popup-modal'));
             
            //Popup appears on winodow load only once in session
            $( document ).ready(function() {
                    var cookieGet = Cookies.getJSON('amishown');
                    if (cookieGet === null || cookieGet === undefined){
                    $("#popup-modal").modal("openModal");
	            var cookieSet = Cookies.set('amishown', 'shown');
                    } 
             });
        }
    );
</script>