What's your biggest current challenge? Have your say in Community Polls along the right column.

How can I insert dynamic values in Javascript with App Embed Blocks?

How can I insert dynamic values in Javascript with App Embed Blocks?

Britainjs
Shopify Partner
2 0 1

Hello,

 

We are currently in the process of moving our app installation from using Script Tags/Assets to App Embed Blocks. Our app primarily just inserts Javascript into the head of the theme. The problem I am running into is that our Javascript requires dynamic values that are unique for each store. With Assets it was trivial to make those values dynamic, but I don't see any way to do this with App Embed Blocks/Theme Extensions. Our Javascript will not function without these values. It seems like other users have run into this issue without much luck (https://community.shopify.com/c/shopify-apis-and-sdks/add-dynamic-javascript/m-p/1386619, https://community.shopify.com/c/shopify-apis-and-sdks/can-app-blocks-be-different-for-each-store-ins...). 

 

Hoping someone can advise us here.

 

Thanks!

Replies 4 (4)

AndyHung
Shopify Partner
63 0 16

Hello @Britainjs ,

I'm facing the same your issue. Did you have any solution? Please help me

Best Regards

corbenisboring
Shopify Partner
3 0 0

any luck with this?

Britainjs
Shopify Partner
2 0 1

We put the migration on hold for a while, but we were able to eventually find a solution in App Data Metafields (https://shopify.dev/docs/apps/custom-data/metafields/app-data). We set the metafields during the app installation process and are then able to reference them using the app.metafields liquid variables. For example:

{{ app.metafields.<namespace>.secretKey.value }}

ShaunStarttin
Shopify Partner
20 3 4

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).