rosyred33 parker
rosyred33 parker

Reputation: 25

Firing custom event on iframe src change

I am trying to fire conversion event if the iframe src changes as follows:

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");
}

and then

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

All good and the script gets added to the div tag but the conversion is not firing the conversion in tag assistant.

I have also initially tried to fire the code without script like this:

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");
}

But I would get gtag is not defined

What am i missing?

Upvotes: 0

Views: 157

Answers (1)

Filipizaum
Filipizaum

Reputation: 81

According this post, in order to listen to attribute changes, you would need a 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
});

Don't forget to add gatg javascript to your page (you are probably trying to route data to groups and properties):

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

Upvotes: 0

Related Questions