javascriptjs-cookie

"Cookies not defined" in standalone js-cookie javascript lib?


I am not a javascript guru, but try to use js-cookie. I included the script: https://github.com/js-cookie/js-cookie: I downloaded it (LINK), and put it in my own js file on the server. I then include it in a test file and read some cookie, but it keeps showing me the error "Cookies is not defined" in the browser console. What am I doing wrong :( ? Code:

<html><head>
<script type="javascript" src="https://server/cookies.js"></script>
<script>
console.log("ALL COOKIES: " + Cookies.get());
</script></head>
<body></body>

Solution

  • I've not used the library, but a quick look at the source code shows that it exports Cookies with an uppercase C.

        if (!registeredInModuleLoader) {
            var OldCookies = window.Cookies;
            var api = window.Cookies = factory();
            api.noConflict = function () {
                window.Cookies = OldCookies;
                return api;
            };
        }
    

    So try using the correct case.

     console.log("ALL COOKIES: " + window.Cookies.get());
    

    Also, everything on window is global. So you can simplify the code to this.

     console.log("ALL COOKIES: " + Cookies.get());
    

    Next time, in the JavaScript console on the browser. Just type window and enter to see what variables are global. You can also call it directly in the console to see what happens Cookies should print out a JavaScript object with descriptions of what functions it has.

    If it's undefined then it wasn't loaded or is not global.

    UPDATED:

    The browser is not loading the JavaScript library because the mime-type is wrong. You have to use application/javascript as here:

          <script type="application/javascript" src="https://server/cookies.js"></script>