首页 > 解决方案 > 在 iframe src 更改上触发自定义事件

问题描述

如果 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 未定义

我错过了什么?

标签: javascriptjquery

解决方案


根据这篇文章,为了监听属性变化,你需要一个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>

推荐阅读