Getting the current variant from JavaScript

Highlighted
New Member
2 0 0

One of the key features of our app is that it’s incredibly easy to install - no liquid editing required. We automatically inject ourselves onto the page (at runtime via ScriptTag) and everything “just works”.

Here’s the catch though: because we’re injecting ourselves onto the page, we need a way of figuring out which variant the customer is currently looking at. Initially we were loo
king at the URL to get the product’s handle (and optionally, the variant ID if it’s up there). That didn’t work for every site, so we ended up using a window property: 

 

ShopifyAnalytics.meta.selectedVariantId


As far as we could tell, the selectedVariantId from that object was working pretty well. Curiously, it was sometimes null (which doesn’t make much sense), but we added a fallback to use the URL when it was empty and everything seemed fine.

A few days ago though, we had a very angry merchant complaining that our app was showing information for the wrong product. I went to check it out, and it turns out that the ShopifyAnalytics.meta.selectedVariantId on their site is actually completely wrong. It changes with each item, but as far as I can tell it’s always the wrong product. Here’s an example:
https://www.motionrc.com/collections/scratch-and-dent-items/products/freewing-f-a-18c-hornet-blue-an...

My question is really two-fold:
1) Is there a better way to dynamically get the current variant, or is this the right way?
2) If it is the right way, why is it sometimes empty (or apparently sometimes even wrong)?

0 Likes
Shopify Expert
9765 86 1516

There’s no way to determine this without identifying the value that will either be passed in the form post, or handled by whatever Ajax functions are in place. The ability for a merchant to completely customise the theme means that you won’t be able to just drop in code and have it work every time. For example you might find a page that is completely built with JS and has zero fields in place at all to try and capture.

 

Expect to have to customise the code you’re running.

 

Also, trying to hijack data in that analytics object is a crazy idea. If it’s not documented, you should never rely on it.
It could very easily be renamed, changed, or removed without warning just like you’ve seen. 

★ Winning Partner of the Build a Business competition. ★ http://freakdesign.com.au
0 Likes