Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
33
rated 0 times [  34] [ 1]  / answers: 1 / hits: 5333  / 5 Years ago, fri, september 6, 2019, 12:00:00

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?


More From » jquery

 Answers
2

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>

[#6331] Tuesday, September 3, 2019, 5 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daja

Total Points: 407
Total Questions: 103
Total Answers: 103

Location: Ghana
Member since Sun, Mar 27, 2022
2 Years ago
daja questions
Tue, Dec 21, 21, 00:00, 2 Years ago
Thu, Apr 23, 20, 00:00, 4 Years ago
Tue, Jul 23, 19, 00:00, 5 Years ago
Sat, Apr 27, 19, 00:00, 5 Years ago
;