javascript - 在 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 未定义
我错过了什么?
解决方案
根据这篇文章,为了监听属性变化,你需要一个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>
推荐阅读
- python - 如何在 tkinter 中一个接一个地显示一个单词
- node.js - node.js 如何在另一个中使用 app.get 变量
- vue.js - 如何在 vue3 中使用 Realm SDK
- python - 使用 pip 安装了 python 包,但无法导入该包
- flutter - 所有异步小部件都返回 null
- android - 带有项目单击侦听器的列表视图在搜索视图中获取错误数据
- sql - Hibernate 查询获取对象列表,每个所需对象都在其他对象列表中。该列表是另一个对象的一部分
- c++ - C++ Paho MQTT 连接作为订阅者问题
- r - 如何在 R Shiny 应用程序中显示我的 R Shiny 代码?
- rust - 为什么“临时是块末尾表达式的一部分”是一个错误?