An advertiser inserts an iframe on my website in the Dom via an external script. The content of the iframe takes a long time to load the browser. I want, that as soon as the iframe appears in the dom, the iframe is removed again. The iframe has no ID.
My solution so far is setInterval. I check a total of 10 times at intervals of 600ms whether the iframe has been inserted and if so, then remove the iframe and stop the interval. I dont like working with setInterval for performance issues and would rather use addeventlistener or mutationobserver but it doesn't work.
This is what I have at the moment and it works:
var removeRun = 0;
  intervalremove = setInterval(function () {
    removeRun += 1;
    if (removeRun === 10) {
      clearInterval(intervalremove);
    }
    
    
    if($("iframe[src*='//ad.adserver.cy']").length == 1) {
    console.log('dom contains adserver iframe');
 
    $("iframe[src*='//ad.adserver.cy']").remove();
    clearInterval(intervalremove);
    console.log('iframe removed / interval stoped');
    }
    
    
  }, 600);
I already searched for mutation and addeventlistener and found many sites. e.g. B.
Is there a JavaScript / jQuery DOM change listener?
So far I haven't managed to build any code that works. Thanks for your help.
Here is one of the hundreds mutationobserver codes I tried
   // Select the node that will be observed for mutations
  var target = 
 document.querySelector("iframe[src*='csync.smartadserver.com']");
 // Create an observer instance
 var observer = new MutationObserver(function( mutations ) {
  mutations.forEach(function( mutation ) {
   var newNodes = mutation.addedNodes; // DOM NodeList
    if( newNodes !== null ) { // If there are new nodes added
    console.log('iframe found');
    });
   }
  });    
  });
  // Configuration of the observer:
var config = { 
   attributes: true, 
   childList: true, 
   characterData: true 
  };
 // Pass in the target node, as well as the observer options
observer.observe(target, config);
// Later, you can stop observing
observer.disconnect();
