Reputation: 522
I would like to ask someone who had experience with Shopify App development how to inject JS script into product.template.liquid under "Add to cart button" when a Toggle button is clicked from React component.
I have already set up an app using Node.js and React (Polaris framework) and I can connect and authenticate with Shopify. I also wrote the JS script that is working when I add it directly to the product.template.liquid page. Now I would like to connect these two.
The script is showing a fake count of viewers on the page.
What I would like to do is to display this script if this.state == enabled and hide the script if this.state == disabled.
Thank you very much for your help!
Upvotes: 1
Views: 2439
Reputation: 4930
I don't know how important it is for you to directly add the Script inside product template, but doing so is possible using Asset resource from Shopify REST API. You can update the product.template.liquid file using PUT request. Sample request from Shopify Docs
PUT /admin/api/2020-07/themes/828155753/assets.json
{
"asset": {
"key": "templates/index.liquid",
"value": "<img src='backsoon-postit.png'><p>We are busy updating the store for you and will be back within the hour.</p>"
}
}
Alternatively, you can use ScriptTag to include your JavaScript snippet. You can add and remove Script Tag from client store based on your Toggle button. This solution is much cleaner in my opinion. A sample request from Shopify Docs to create Script Tag.
POST /admin/api/2020-07/script_tags.json
{
"script_tag": {
"event": "onload",
"src": "https://djavaskripped.org/fancy.js"
}
}
Upvotes: 2