2

This might be a little confusing - I'm trying to retrieve the value of a cookie from inside a js file and to do this im using the js-cookie library over a CDN create from the JS file. However Cookies is undefined when i try to access the library.

I'm wondering what the problem is and what my best option is to do this?

var jQueryScript = document.createElement("script");
jQueryScript.setAttribute(
  "src",
  "https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.1/js.cookie.min.js"
);
jQueryScript.setAttribute("type", "module");
document.head.appendChild(jQueryScript);

// Cookies.get is not defined.
var cookieval = Cookies.get("shopOrigin");
console.log(cookieval);

Any help would be much appeciated, it is most likely something simple i am missing. Thanks

1 Answer 1

1
    const loadScript = url => new Promise((resolve, reject) => {
      const node = document.createElement('script')
      node.setAttribute('src', url)
      node.onload = resolve
      node.reject = reject 
      document.body.appendChild(node)
    })

    loadScript('//cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.1/js.cookie.min.js')
      .then(() => {
        // do your job here
        console.log(window.Cookies)
      })
Sign up to request clarification or add additional context in comments.

3 Comments

Still undefined
try post a reproduceable example here
codepen.io/Blewie/pen/rNWBjrx?editors=1111 this is as close as i can get

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.