Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect URL change in querystring

I am adding some script on a Shopify product page where I need to detect the URL change which happens on selection of a product option (handled by Shopify) for further use.

The URL change occurs when variants are selected with the query parameter (question mark) like this:

Variant 1 - my.shopify.domain/products/product1?variant=1234
Variant 2 - my.shopify.domain/products/product1?variant=5678

I have tried adding the 'hashchange' event but then realized it only works for '#' which is not the case here.

What should I do?

like image 874
user3884753 Avatar asked Mar 03 '23 11:03

user3884753


1 Answers

Please paste this script in your product.liquid file

<script>
  var firstTimeUrl = document.URL;
  document.addEventListener('change', function() {
  var currentPageUrl = document.URL;
  var url = new URL(currentPageUrl);
  var isVariantUrl = url.searchParams.get("variant");
  currentPageUrl = isVariantUrl ? currentPageUrl :isVariantUrl;
    if(currentPageUrl && firstTimeUrl != currentPageUrl) {
      firstTimeUrl = currentPageUrl;
      console.log('variant_id: '+isVariantUrl+'')
    }
  });
</script>
like image 198
ankit singh Avatar answered Mar 06 '23 22:03

ankit singh