Have your say in Community Polls: What was/is your greatest motivation to start your own business?

How to fully remove a discount code from a cookie with JavaScript?

How to fully remove a discount code from a cookie with JavaScript?

spencerwatson
Shopify Partner
3 0 1

First let me explain what this JavaScript script does and then in bold I will explain my problem.

The script observes a Shopify cookie named 'discount_code'. It starts by declaring helper functions to get and set cookies. It then attempts to fetch the 'discount_code' cookie and store its value. If the 'discount_code' cookie is present and not empty, the script displays a message with the discount code on the web page. Otherwise, it hides the message. This check is performed once at the beginning and then repeated every second. If clicked normally, the code gets copied to the user's clipboard.

If the user clicks on the displayed discount code message while holding the alt and shift keys, the 'discount_code' cookie is deleted from the cookie and it is then replaced with an expired cookie. However the discount code still persists when checking out; it isn't the cookie that still persists, so what is it? How do I clear the discount code entirely? Is this something that must be done in the liquid theme?

 

  var codeCookieValue;
  var getCookie = function(name) {
    var value = "; " + document.cookie;
    var parts = value.split('; ' + name + '=');
    if (parts.length == 2) return parts.pop().split(";").shift();
  };
  
  var setCookie = function(name, value, expires) {
    document.cookie = name + "=" + (value || "")  + (expires ? "; expires=" + expires : "") + "; path=/";
  };

  codeCookieValue = getCookie('discount_code');

  var discountMessageElement = document.getElementById('discount-message');
  var copyMessageElement = document.getElementById('copy-message');

  var checkCookieValue = function() {
    var currentCodeCookieValue = getCookie('discount_code');
    
    if (currentCodeCookieValue && currentCodeCookieValue !== '') {
      codeCookieValue = currentCodeCookieValue;
      var introMessage = "Discount Code: ";
      discountMessageElement.innerHTML = introMessage+'<span class="bold">'+codeCookieValue+'</span>';
      discountMessageElement.style.display = "block";
    } else {
      discountMessageElement.style.display = "none";
    }
  };

  checkCookieValue(); // Run immediately

  setInterval(checkCookieValue, 1000); // Then every second

  // Add click event listener
  discountMessageElement.addEventListener('click', function(event) {
      if (!codeCookieValue) return;

      if (event.altKey && event.shiftKey) {
          setCookie('discount_code', '', "Thu, 01 Jan 1970 00:00:00 UTC");
          checkCookieValue();
          return;
      }

      navigator.clipboard.writeText(codeCookieValue).then(function() {
          console.log('Code copied to clipboard!');
          discountMessageElement.classList.add('clicked');
          copyMessageElement.style.display = "block";
          copyMessageElement.style.opacity = "1";
          setTimeout(function() { 
              discountMessageElement.classList.remove('clicked'); 
              copyMessageElement.style.opacity = "0";
              setTimeout(function() { copyMessageElement.style.display = "none"; }, 3000);
          }, 3000);
      }).catch(function(error) {
          console.error('Error copying code to clipboard: ', error);
      });
  });

 

 

Replies 12 (12)

spencerwatson
Shopify Partner
3 0 1

To clarify, the discount code is persisting into the checkout phase after my script supposedly clears the discount code cookie and replaces it with an expired cookie. I would like to ensure that a cleared discount cookie does not persist into the checkout phase.

MaxDesign
Shopify Partner
214 15 88

Unfortunately I don't think that's possible to remove a discount code using "discount_code" cookie, I have tried just like you, but this area is poorly documented. It seems the discount code value is retained in a cookie named "cart". Making this cookie expire before checkout will also result in loosing the cart items, meanwhile in checkout it seems the items are preserved and the discount disappears once the cookie is removed, but there surely might be adverse effect to removing this cookie in checkout.

It is unclear exactly how this cookie is used and what values it retains, but the main take away is that it's not really possible, or at least I'm still curious to find out how.

Reach out to me at admin@maxdesign.expert

flobee
Shopify Partner
1 0 2

Hello,

 

fetch("/discount/CLEAR");

 

this should do the trick 

MaxDesign
Shopify Partner
214 15 88

Neat! May I ask where you found this? Can't find any documentation about this API.

Reach out to me at admin@maxdesign.expert
scottshop
Shopify Partner
9 1 1

What method did you end up using? I am finding some initial success with this:

fetch('/checkout?discount=CLEAR')

 

MaxDesign
Shopify Partner
214 15 88

I use the /discount method, haven't noticed any problem with it. I actually found a more complex approach in here: https://gist.github.com/elghorfi/ce7e5b1080aae37d0a415643f33bc79e and I posted my own method at the bottom of this gist (which is significantly simpler).

Reach out to me at admin@maxdesign.expert
timd_mackey
Shopify Partner
62 1 33
fetch('/discount/CLEAR');

This works great, but I thought I'd chime in to clarify why this actually works. It's not an API call, it's actually just applying a non-existent Discount Code, which has the effect of removing the current discount code. If for some reason you were to create a Discount code called "CLEAR", this wouldn't work, as you can see I've done here:
Screenshot 2024-04-02 at 1.29.02 PM.png

So this method will work great, you just need to ensure that the discount code in your URL doesn't actually exist (and ideally will never exist). I'll probably use something like this instead:

fetch('/discount/REMOVE_DISCOUNT_CODES');

 

midoribi
Shopify Partner
7 0 1

thank you.
Discount code has been removed.

however,
The deleted discount code will remain displayed in the cart. cache?

checkout is no problem, but
Is it better to delete the discount code from the cart Liquid code?

scottshop
Shopify Partner
9 1 1

Try this:

fetch('/checkout?discount=CLEAR')

 

midoribi
Shopify Partner
7 0 1

No Good

 

Cached for approximately 1 hour.

 

check cookie discountcode were changed.

 

but , deleted discount code was displayed .. like zombie : (

 

spencerwatson
Shopify Partner
3 0 1

As far as I can determine, this isn't possible. 

midoribi
Shopify Partner
7 0 1

Thx.

 

In my plugin install,
edit liquid templete:

discount_application -> delete

cart.total_price -> cart.items_subtotal_price

 

That's correct.