天天看点

shopify开发中使用klaviyo邮箱订阅插件遇到的问题,使用轮询监听解决

今天在给客户的开发过程中遇到一个问题,下图

shopify开发中使用klaviyo邮箱订阅插件遇到的问题,使用轮询监听解决

因为使用了klaviyo第三方邮件插件的简单用法,所以在页面生成的时候获取不到元素,插件实例化成功以后才会在这个容器中插入相关的功能代码。

所以解决这个问题可以使用计时器轮询监听是否已经实例化完成,然后为form表单添加监听事件改变hash值。

<div class="klaviyo-form-xxxxxxxx">
    插件实例化成功以后才会在这个容器中插入相关的功能代码
</div>
  
<script>

// 轮询监听底部邮件实例化
  let nIntervId;

  function listen_form() {
    if (!nIntervId) {
      nIntervId = setInterval(flashText, 300);
    }
  }

  function flashText() {
    const oElem = $('.klaviyo-form-Y2vs6e form')
    if (oElem) {
      console.log('已经监听表单实例化成功===停止')

      {% comment %} 添加监听表单 {% endcomment %}
      window.addEventListener("klaviyoForms", function(e) { 
        console.dir('获取事件对象',e)

        if (e.detail.type == 'submit') {
          console.log('成功')
          window.location.hash = "bottom_email_success"
        }
      });
      stop_listen_form()

    } else {


      console.log('监听表单实例化成功')
      
    }
  }

  function stop_listen_form() {
    clearInterval(nIntervId);
    // release our intervalID from the variable
    nIntervId = null; 
  }

  listen_form()

</script>
           

继续阅读