Re: Access store products data from Javascript asset file

Access store products data from Javascript asset file

AlonsoValls
Shopify Partner
1 0 0

Let's say I want to replace the Home Page with a 3D experience using a JavaScript library (https://threejs.org/).

I call the javascript file that contains the experience, from the home page .liquid file. I call it from a script tag with type="module".

How could I from the javascript file access the products active for sale data?
I would just need to print on the console a URL path to its main image, the price, and the name of 10 products, I don't really mind about the order of them. 

 

Thanks for your help and sorry if this is a beginner question.

Reply 1 (1)

ShaunStarttin
Shopify Partner
11 2 2

You could scrape the DOM from JS, but it'd be brittle depending on the theme. You could support a few common themes/structure then have configuration to cover the rest. Also, you could use a `product_list` setting for the block, but it'd be static because I don't think you can place the block so that you get autofill from any sections (e.g. collections)!

 

Finally, for passing the data from liquid block to JS:

 

The easiest way seems to be defining a global variable on `window` in your liquid file and reading it in JS assets. You could also have a top-level unique name to avoid collisions and wrap a bunch of variables. Your liquid block:

 

 

<script>
window.MY_APP_NAME = { customerId: "{{customer.id}}" }
</script>

 

 

Alternately, a Shopify demo uses html attributes and reads them from the DOM (liquid block and js asset). This seems useful to find specific pieces of data in the DOM structure (e.g. loop over all products).