天天看點

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>
           

繼續閱讀