Set cookie in MTurk HIT

67 Views Asked by At

I recently had issues using javascript cookies inside an MTurk HIT. In particular I'm trying to track user preferences w.r.t showing/hiding the HIT instruction.

My approach so far is the following:

<body>
    <div id='instructionButton'>
        <!-- Button triggering instruction body to collapse/show -->
    </div>
    <div id='instructionBody'>
        <!-- Instruction content (collapsible) -->
        ...
    </div>
</body>
<script>
    const instructionBodyId = 'instructionBody';
    const instructionButtonId = 'instructionButton';

    const cookieName = 'my_cookie_name';
    var isInstructionShown = true;

    var instrContent = $('#' + instructionBodyId);
    var instrButton = $('#' + instructionButtonId);


    function setCookie(name, value) {
        var date = new Date();
        <!-- Cookie valid for 48h -->
        date.setTime(date.getTime() + (48 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toUTCString();
        document.cookie = name + "=" + value + expires + "; path=/";
    }

    function getCookie(name) {
        var nameEQ = name + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i];
            while (c.charAt(0) == ' ') c = c.substring(1, c.length);
            if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
        }
        return null;
    }

    function toggleInstructions(isShow) {
        setCookie(cookieName, isShow);
        isInstructionShown = isShow;

        if (isShow) {
            instrContent.slideDown();
        } else {
            instrContent.slideUp();
        }
    }

    function prepare_cookie() {
        instrButton.click(function() {
            toggleInstructions(!isInstructionShown);
        });

        let cookieVal = getCookie(cookieName);
        if (cookieVal == "false") {
            toggleInstructions(false);
        } else {
            toggleInstructions(true);
        }
    }

    $(document).ready(function() {
        prepare_cookie();
    });
</script>

The code above shows part of the HIT layout I'm creating, and when testing it out while editing the HIT directly in MTurk, the cookie works as expected (it shows up in Google Chrome and works as expected, showing/hiding the instruction automatically).

Unfortunately, when publishing the HIT, the cookie does not seem to be set (it does not appear in the list of cookies shown in Google Chrome).

0

There are 0 best solutions below