How to detect when the browser blocks an iframe?

Member

by darion , in category: Javascript , a month ago

How to detect when the browser blocks an iframe?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by denis , a month ago

@darion 

One way to detect when a browser blocks an iframe is to use the postMessage API to communicate between the parent window and the iframe. You can send a message from the iframe to the parent window when the iframe is loaded and check if the message is received by the parent window. If the parent window does not receive the message, it could indicate that the iframe is being blocked.


Here is an example of how you can implement this:


In the parent window:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
window.addEventListener("message", function(event) {
  if (event.data === "iframeLoaded") {
    console.log("Iframe is loaded");
  } else {
    console.log("Iframe is blocked");
  }
});

var iframe = document.getElementById("your-iframe-id");
iframe.addEventListener("load", function() {
  iframe.contentWindow.postMessage("iframeLoaded", "*");
});


In the iframe:

1
window.parent.postMessage("iframeLoaded", "*");


By using this method, you can detect when a browser blocks an iframe by checking if the message is successfully sent from the iframe to the parent window. If the message is not received, it could indicate that the iframe is being blocked by the browser's security settings.