SHOPIFY: JS Cookie Set in the Product page but not retrieve on cart page

374 Views Asked by At

Actually, I want to store the latest product URL in the cookie, so If the user clicks on the CONTINUE SHOPPING button on the cart page, it redirects to the last access product page. If the cookie has the value then the user redirects otherwise, it redirects to the SHOP page.

Here is the code, that I applied.

<script src="https://code.jquery.com/jquery-3.7.0.js" type="text/javascript"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js" type="text/javascript"></script>
<script type="text/javascript">
    if (window.location.href.indexOf("products") > -1) {
      var latestProductUrl = window. location.href; 
      $.cookie("lastProductUrl", latestProductUrl);
      console.log('Success '+$.cookie("lastProductUrl"));
    }
    else if(window.location.href.indexOf("cart") > -1){
        console.log('here:'+$.cookie("lastProductUrl"));
    }
   
 </script>

It shows me in the console. Success: defined and retrieved. Here: Undefined.

1

There are 1 best solutions below

4
Developer On BEST ANSWER

As $.cookie is not a part of jQuery library and for using $.cookie, you need a jquery-cookie.

Don't use this plugin. It is deprecated now and it is supersededby JS Cookie. You can read on GitHub repository of jquery-cookie plugin that it is superseded by JS Cookie. JS Cookie is a Javascript API for handling browser cookies.

Here is the updated code using JS Cookie:-

<script src="https://code.jquery.com/jquery-3.7.0.js" type="text/javascript"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js.cookie.min.js"></script>
<script type="text/javascript">
    if (window.location.href.indexOf("products") > -1) {
      var latestProductUrl = window. location.href; 
      Cookies.set("lastProductUrl", latestProductUrl);
      console.log('Success '+Cookies.get("lastProductUrl"));
    }
    else if(window.location.href.indexOf("cart") > -1){
        console.log('here:'+Cookies.get("lastProductUrl"));
    }
 </script>

Note that:-

  • As I am using JS Cookie so the CDN is changed.
  • The syntax for storing and retrieving the cookie value is also changed.

You can read about it more in the JS Cookie GitHub repository. Hope it will be helpful.