ScriptTag - Detect it the product variant has been changed.

Shopify Partner
2 0 0

Hi all,

I am building an app which injects a new button in the product page using ScriptTag.

The problem is that, sometimes, I would like to show that button for some specific product variants and to hide it for the rest. 

I know that the variant ID is in the query params in the URL (e.g. .../products/<product_handle>?variant=<variantId>) but I don't know how to detect when this changes. For examples, let's say the customer is on the product page /products/productName?variant=1 and they choose a different size (small ->medium). The URL is automatically updated to /products/productName?variant=2. 

I tried to use the "hashchange" listener to trigger when the URL has changed but it did not work. I read about the OptionSelectors() approach but I would like to avoid editing every shop's theme file.

Does anyone know how to automatically detect (using vanilla JS or any other method) when the product variant has been changed?


12 1 4

Personally I would create a setInterval that checks the href. I did not found any other reliable solution other than that. Hope it helps.