简体   繁体   English

如何与 Shopify Storefront 通信并将 JS 片段添加到产品页面

[英]How to communicate with Shopify Storefront and add JS snippet to Product Page

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.我想问一下有Shopify App开发经验的人,当从React组件单击切换按钮时,如何在“添加到购物车按钮”下将JS脚本注入product.template.liquid。

I have already set up an app using Node.js and React (Polaris framework) and I can connect and authenticate with Shopify.我已经使用 Node.js 和 React(Polaris 框架)设置了一个应用程序,我可以使用 Shopify 进行连接和身份验证。 I also wrote the JS script that is working when I add it directly to the product.template.liquid page.当我将它直接添加到 product.template.liquid 页面时,我还编写了正在运行的 JS 脚本。 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.如果 this.state == 启用,我想做的是显示这个脚本,如果 this.state == 禁用,则隐藏脚本。

Thank you very much for your help!非常感谢您的帮助!

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.我不知道直接在产品模板中添加脚本对您来说有多重要,但是可以使用来自 Shopify REST API 的资产资源来这样做。 You can update the product.template.liquid file using PUT request.您可以使用PUT请求更新product.template.liquid文件。 Sample request from Shopify Docs来自Shopify 文档的样品请求

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.或者,您可以使用 ScriptTag 来包含您的 JavaScript 代码段。 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 .来自 Shopify Docs 的示例请求以创建Script Tag

POST /admin/api/2020-07/script_tags.json
{
  "script_tag": {
    "event": "onload",
    "src": "https://djavaskripped.org/fancy.js"
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM