簡體   English   中英

在 iframe src 更改上觸發自定義事件

[英]Firing custom event on iframe src change

如果 iframe src 更改如下,我將嘗試觸發轉換事件:

var src = document.getElementById("iframeID").src; // get the src
var url = "https://example.com/?123"

if(src.indexOf(url) !=-1){ //this will return -1 if false

document.getElementById("myid").innerHTML = "<script>gtag('event', 'conversion', {'send_to': 'AW-xyz/xyz'});<\/script>";

}else{
    alert("wrong url");
}

接着

<div id="myid"></div>

一切都好,腳本被添加到 div 標簽,但轉換沒有在標簽助手中觸發轉換。

我最初也嘗試在沒有腳本的情況下觸發代碼,如下所示:

var src = document.getElementById("iframeID").src; // get the src
var url = "https://example.com/?123"

if(src.indexOf(url) !=-1){ //this will return -1 if false

gtag('event', 'conversion', {'send_to': 'AW-xyz/xyz'});

}else{
    alert("wrong url");
}

但我會得到 gtag 未定義

我錯過了什么?

根據這篇文章,為了監聽屬性變化,你需要一個MutationObserver


var iframe = document.getElementById("iframeID");
iframe.setAttribute('data-oldsrc', iframe.getAttribute('src'));
var url = "https://example.com/?123"

var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        if (mutation.type == "attributes") {
            var src = iframe.src; // get the src
            if(iframe.getAttribute('data-oldsrc')){ // If the mutation is in 'src'
                if(src.indexOf(url) !=-1){ // If the src contains the url
                    // Trigger event
                    gtag('event', 'conversion', {'send_to': 'AW-xyz/xyz'});

                }else{
                    alert("wrong url");
                }
            }
            
        }
    })
});

observer.observe(element, {
  attributes: true //configure it to listen to attribute changes
});

不要忘記將 gatg javascript 添加到您的頁面(您可能正在嘗試將數據路由到組和屬性):

<script async src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID"></script>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM