1

我正在构建一个网站,当单击“添加到购物车”按钮时,我想在其中运行辅助功能。

出于某种原因,当我尝试使用任何类型的事件侦听器或 getElementsbyTagName 来访问由 BuyButton 脚本创建的按钮时,它总是以未定义的形式返回并给我这个错误:

未捕获的类型错误:无法设置未定义的属性(设置“innerHTML”)

这是我的代码:

   <script src="http://sdks.shopifycdn.com/buy-button/1.0.0/buybutton.js" ></script>    
</head>
<body>
    <div id="shopifyDiv"></div>


    <script type="text/javascript">
    /*<![CDATA[*/
        var client = ShopifyBuy.buildClient({
          domain: 'shopify.myshopify.com',
          storefrontAccessToken: '(myTokenHere)',
        });

        var ui = ShopifyBuy.UI.init(client);

        
        ui.createComponent('product', {
        id: (myIdHere),
        node: document.getElementById('shopifyDiv'),
        options: {
            product:{
              width: '350px',
              contents:{
                img: false,
                button: true,
                title: false
              },
              text: {
          button: 'Add to cart'
        },
            },
          cart:{
            startOpen: false
          },

        }
      
      });


    /*]]>*/
    </script>



  <script type="module">

document.getElementsByTagName('button')[0].innerHTML = 'hello world';

       </script>
    
</body>
</html>

出于安全目的,我删除了 Shopify 特定的 accessToken 和域名。

任何有助于理解 Shopify 脚本创建的这些 DOM 元素为何无法访问的帮助将不胜感激。

4

1 回答 1

0

Shopify BuyButton 在您的元素内生成一个 iframe。

这意味着两件事:

  • 您需要等待元素出现在 DOM 中(因为这会产生异步请求,所以您无法在 DOM 就绪时访问它)
  • 您需要获取 iframe 的内容才能获取按钮

因此,您需要将 a 链接.then到您的组件创建方法,如下所示:

ui.createComponent('product', {
  // your original code
}).then((res) => {
  const iframe = document.querySelector('#shopifyDiv iframe').contentDocument;
  iframe.querySelector('button').innerHTML = 'hello world';
});

以其中的 iframe 内容为目标,然后执行您的逻辑。

这就是你所要做的。

于 2022-02-03T22:10:55.647 回答