How to detect when the BROWSER blocks an iFrame

2020-03-05 06:47发布

问题:

On an https website, I'm trying to load randomly submitted URLs into an iframe, allowing the user to see that website embedded in my own user interface.

As long as the remote url is https (like my own site), and the remote server doesn't explicitly block itself from being embedded in iframes, the website displays fine within the iframe. I know how to create a server-side script that can pre-detect if the iframe will be blocked due to the 3rd party's intentional iframe-blocking.

However, there are a number of reasons that the iframe gets blocked by the browser (an not by the 3rd party server):

  1. If the remote url is not https, or forwards to a non-https url, it will be blocked (by the browser) from displaying in the iframe.
  2. If the remote site is indeed https, but contains at least one resource served by http (instead of https), the browser will block the iframe due to mixed content.

My question is specifically this: how can I detect with client-side javascript, when the browser has blocked the iframe. I want my client-side javascript to detect the block and the reason for the block (which I know how to log, if I can detect it).

In summary, I already know how to detect when the 3rd party blocks the iframe (using server-side scripting), I'm only interested in answers that show how to detect when the web browser is doing the blocking and how to detect that with client-side javascript.

I can see these non-fatal blocks in the console (shift-ctrl-i), but I do not know how to programmatically detect them during run-time and then gracefully handle the blocks by providing a message of why it was block and a link so that the user can open the resource in a new tab. For example, typically I catch errors with try/catch statements, but I don't know how to catch these browser-level errors that occur due to the iframe src-location, that seem to only appear in the console.

My priority is, displaying the page in the iframe every time it is not blocked, and programmatically doing something else each time it is blocked.

This doesn't work, but it is an example of something I tried:

window.addEventListener('error', function(event)
{
    console.log(`Caught Using Javascript`, event);
});

The error shows up in the console, but "Caught Using Javascript" does not: