如何检查iframe是否被加载或它有内容?

时间:2022-10-06 00:03:28

I have an iframe with id = "myIframe" and here my code to load it's content :

我有一个id = "myIframe"的iframe,这里我要加载的代码是:

$('#myIframe').attr("src", "my_url");

The problem is sometimes it take too long for loading and sometimes it loaded very quickly. So I must to use "setTimeout" function :

问题是,有时加载时间过长,有时加载速度很快。所以我必须使用"setTimeout"函数:

setTimeout(function(){
   if (//something shows iframe is loaded or has content)
   {
       //my code
   }
   else
   {
       $('#myIframe').attr("src",""); //stop loading content
   }
},5000);

All I want to know is how to find out if an iFrame is loaded or it has content. Using iframe.contents().find() will not work. I can't use iframe.load(function(){}).

我想知道的是,如何找出一个iFrame是被加载的还是有内容的。使用iframe.contents().find()将不起作用。我不能用iframe.load(函数(){ })。

9 个解决方案

#1


56  

Try this.

试试这个。

<script>
function checkIframeLoaded() {
    // Get a handle to the iframe element
    var iframe = document.getElementById('i_frame');
    var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;

    // Check if loading is complete
    if (  iframeDoc.readyState  == 'complete' ) {
        //iframe.contentWindow.alert("Hello");
        iframe.contentWindow.onload = function(){
            alert("I am loaded");
        };
        // The loading is complete, call the function we want executed once the iframe is loaded
        afterLoading();
        return;
    } 

    // If we are here, it is not loaded. Set things up so we check   the status again in 100 milliseconds
    window.setTimeout(checkIframeLoaded, 100);
}

function afterLoading(){
    alert("I am here");
}
</script>

<body onload="checkIframeLoaded();"> 

#2


33  

kindly use:

请使用:

$('#myIframe').on('load', function(){
    //your code (will be called once iframe is done loading)
});

Updated my answer as the standards changed.

随着标准的改变,我更新了我的答案。

#3


10  

Easiest option:

简单的选择:

<script type="text/javascript">
  function frameload(){
   alert("iframe loaded")
  }
</script>

<iframe onload="frameload()" src=...>

#4


5  

I had the same issue and added to this, i needed to check if iframe is loaded irrespective of cross-domain policy. I was developing a chrome extension which injects certain script on a webpage and displays some content from the parent page in an iframe. I tried following approach and this worked perfect for me.
P.S.: In my case, i do have control over content in iframe but not on the parent site. (Iframe is hosted on my own server)

First:
Create an iframe with a data- attribute in it like (this part was in injected script in my case)
<iframe id="myiframe" src="http://anyurl.com" data-isloaded="0"></iframe>

Now in the iframe code, use :

我有相同的问题并添加到这个问题,我需要检查iframe是否加载,而不考虑跨域策略。我正在开发一个chrome扩展,它在网页上注入某些脚本,并在iframe中显示一些来自父页面的内容。我试着遵循这种方法,这对我来说是完美的。注::在我的情况下,我确实可以控制iframe中的内容,但不能控制父站点的内容。(Iframe托管在我自己的服务器上)首先:创建一个带有数据属性的Iframe(在我的例子中,这部分是注入脚本)< Iframe id="myiframe" src="http://anyurl.com" ="0"> 现在在Iframe代码中,使用:

var sourceURL = document.referrer;
window.parent.postMessage('1',sourceURL);



Now back to the injected script as per my case:

现在根据我的情况回到注入脚本:

setTimeout(function(){
  var myIframe = document.getElementById('myiframe');
  var isLoaded = myIframe.prop('data-isloaded');
  if(isLoaded != '1')
  {
    console.log('iframe failed to load');
  } else {
    console.log('iframe loaded');
  }
},3000);


and,

而且,

window.addEventListener("message", receiveMessage, false);
function receiveMessage(event)
{
    if(event.origin !== 'https://someWebsite.com') //check origin of message for security reasons
    {
        console.log('URL issues');
        return;
    }
    else {
        var myMsg = event.data;
        if(myMsg == '1'){
            $("#myiframe").prop('data-isload', '1');
        }
    }           
}



It may not exactly answer the question but it indeed is a possible case of this question which i solved by this method.

它也许不能确切地回答这个问题,但它确实是我用这种方法解决的这个问题的一种可能的情况。

#5


5  

I'm not sure if you can detect whether it's loaded or not, but you can fire an event once it's done loading:

我不确定你是否可以检测它是否被加载,但是一旦加载完成,你就可以启动一个事件:

$(function(){
    $('#myIframe').ready(function(){
        //your code (will be called once iframe is done loading)
    });
});

EDIT: As pointed out by Jesse Hallett, this will always fire when the iframe has loaded, even if it already has. So essentially, if the iframe has already loaded, the callback will execute immediately.

编辑:正如Jesse Hallett指出的那样,当iframe已经加载时,即使它已经加载了,它仍然会触发。所以本质上,如果iframe已经加载,回调将立即执行。

#6


3  

You can use the iframe's load event to respond when the iframe loads.

您可以使用iframe的load事件来响应iframe加载。

document.querySelector('iframe').onload = function(){
    console.log('iframe loaded');
};

This won't tell you whether the correct content loaded: To check that, you can inspect the contentDocument.

这不会告诉您是否加载了正确的内容:要检查它,您可以检查contentDocument。

document.querySelector('iframe').onload = function(){
    var iframeBody = this.contentDocument.body;
    console.log('iframe loaded, body is: ', body);
};

Checking the contentDocument won't work if the iframe src points to a different domain from where your code is running.

如果iframe src指向与代码运行位置不同的域,则检查contentDocument将不起作用。

#7


1  

When an iFrame loads, it initially contains the #document, so checking the load state might best work by checking what's there now..

当iFrame加载时,它最初包含#文档,所以检查当前的加载状态可能是最好的方法。

if ($('iframe').contents().find('body').children().length > 0) {
    // is loaded
} else {
    // is not loaded
}

#8


1  

in my case it was a cross-origin frame and wasn't loading sometimes. the solution that worked for me is: if it's loaded successfully then if you try this code:

在我的例子中,它是一个交叉原点的框架,有时不加载。对我起作用的解决方案是:如果加载成功,那么如果您尝试以下代码:

var iframe = document.getElementsByTagName('iframe')[0];
console.log(iframe.contentDocument);

it won't allow you to access contentDocument and throw a cross-origin error however if frame is not loaded successfully then contentDocument will return a #document object

它不允许您访问contentDocument并抛出一个跨源错误,但是如果没有成功加载框架,那么contentDocument将返回一个#document对象

#9


1  

A really great method is use jQuery AJAX. The parent frame would look like this:

一个非常好的方法是使用jQuery AJAX。父框架看起来是这样的:

<iframe src="iframe_load.php" style="width: 100%; height: 100%;"></iframe>

The iframe_load.php file would load the jQuery library and a JavaScript that attempts to load the destination URL in an AJAX GET:

iframe_load。php文件将加载jQuery库和试图在AJAX GET中加载目标URL的JavaScript:

var the_url_to_load = "http://www.your-website.com" ;
$.ajax({
            type: "GET",
            url: the_url_to_load,
            data: "",
            success: function(data){
                // if can load inside iframe, load the URL
                location.href = the_url_to_load ;
            },
            statusCode: {
                500: function() {
                    alert( 'site has errors' ) ;
                }
            },
            error:function (xhr, ajaxOptions, thrownError){
                // if x-frame-options, site is down or web server is down
                alert( 'URL did not load due to x-frame-options' ) ;
            } });

IMPORTANT The destination must have contain the "Access-Control-Allow-Origin" header. Example in PHP:

重要的是,目标必须包含“访问控制允许的来源”头。在PHP示例:

HEADER( "Access-Control-Allow-Origin: *" ) ;

#1


56  

Try this.

试试这个。

<script>
function checkIframeLoaded() {
    // Get a handle to the iframe element
    var iframe = document.getElementById('i_frame');
    var iframeDoc = iframe.contentDocument || iframe.contentWindow.document;

    // Check if loading is complete
    if (  iframeDoc.readyState  == 'complete' ) {
        //iframe.contentWindow.alert("Hello");
        iframe.contentWindow.onload = function(){
            alert("I am loaded");
        };
        // The loading is complete, call the function we want executed once the iframe is loaded
        afterLoading();
        return;
    } 

    // If we are here, it is not loaded. Set things up so we check   the status again in 100 milliseconds
    window.setTimeout(checkIframeLoaded, 100);
}

function afterLoading(){
    alert("I am here");
}
</script>

<body onload="checkIframeLoaded();"> 

#2


33  

kindly use:

请使用:

$('#myIframe').on('load', function(){
    //your code (will be called once iframe is done loading)
});

Updated my answer as the standards changed.

随着标准的改变,我更新了我的答案。

#3


10  

Easiest option:

简单的选择:

<script type="text/javascript">
  function frameload(){
   alert("iframe loaded")
  }
</script>

<iframe onload="frameload()" src=...>

#4


5  

I had the same issue and added to this, i needed to check if iframe is loaded irrespective of cross-domain policy. I was developing a chrome extension which injects certain script on a webpage and displays some content from the parent page in an iframe. I tried following approach and this worked perfect for me.
P.S.: In my case, i do have control over content in iframe but not on the parent site. (Iframe is hosted on my own server)

First:
Create an iframe with a data- attribute in it like (this part was in injected script in my case)
<iframe id="myiframe" src="http://anyurl.com" data-isloaded="0"></iframe>

Now in the iframe code, use :

我有相同的问题并添加到这个问题,我需要检查iframe是否加载,而不考虑跨域策略。我正在开发一个chrome扩展,它在网页上注入某些脚本,并在iframe中显示一些来自父页面的内容。我试着遵循这种方法,这对我来说是完美的。注::在我的情况下,我确实可以控制iframe中的内容,但不能控制父站点的内容。(Iframe托管在我自己的服务器上)首先:创建一个带有数据属性的Iframe(在我的例子中,这部分是注入脚本)< Iframe id="myiframe" src="http://anyurl.com" ="0"> 现在在Iframe代码中,使用:

var sourceURL = document.referrer;
window.parent.postMessage('1',sourceURL);



Now back to the injected script as per my case:

现在根据我的情况回到注入脚本:

setTimeout(function(){
  var myIframe = document.getElementById('myiframe');
  var isLoaded = myIframe.prop('data-isloaded');
  if(isLoaded != '1')
  {
    console.log('iframe failed to load');
  } else {
    console.log('iframe loaded');
  }
},3000);


and,

而且,

window.addEventListener("message", receiveMessage, false);
function receiveMessage(event)
{
    if(event.origin !== 'https://someWebsite.com') //check origin of message for security reasons
    {
        console.log('URL issues');
        return;
    }
    else {
        var myMsg = event.data;
        if(myMsg == '1'){
            $("#myiframe").prop('data-isload', '1');
        }
    }           
}



It may not exactly answer the question but it indeed is a possible case of this question which i solved by this method.

它也许不能确切地回答这个问题,但它确实是我用这种方法解决的这个问题的一种可能的情况。

#5


5  

I'm not sure if you can detect whether it's loaded or not, but you can fire an event once it's done loading:

我不确定你是否可以检测它是否被加载,但是一旦加载完成,你就可以启动一个事件:

$(function(){
    $('#myIframe').ready(function(){
        //your code (will be called once iframe is done loading)
    });
});

EDIT: As pointed out by Jesse Hallett, this will always fire when the iframe has loaded, even if it already has. So essentially, if the iframe has already loaded, the callback will execute immediately.

编辑:正如Jesse Hallett指出的那样,当iframe已经加载时,即使它已经加载了,它仍然会触发。所以本质上,如果iframe已经加载,回调将立即执行。

#6


3  

You can use the iframe's load event to respond when the iframe loads.

您可以使用iframe的load事件来响应iframe加载。

document.querySelector('iframe').onload = function(){
    console.log('iframe loaded');
};

This won't tell you whether the correct content loaded: To check that, you can inspect the contentDocument.

这不会告诉您是否加载了正确的内容:要检查它,您可以检查contentDocument。

document.querySelector('iframe').onload = function(){
    var iframeBody = this.contentDocument.body;
    console.log('iframe loaded, body is: ', body);
};

Checking the contentDocument won't work if the iframe src points to a different domain from where your code is running.

如果iframe src指向与代码运行位置不同的域,则检查contentDocument将不起作用。

#7


1  

When an iFrame loads, it initially contains the #document, so checking the load state might best work by checking what's there now..

当iFrame加载时,它最初包含#文档,所以检查当前的加载状态可能是最好的方法。

if ($('iframe').contents().find('body').children().length > 0) {
    // is loaded
} else {
    // is not loaded
}

#8


1  

in my case it was a cross-origin frame and wasn't loading sometimes. the solution that worked for me is: if it's loaded successfully then if you try this code:

在我的例子中,它是一个交叉原点的框架,有时不加载。对我起作用的解决方案是:如果加载成功,那么如果您尝试以下代码:

var iframe = document.getElementsByTagName('iframe')[0];
console.log(iframe.contentDocument);

it won't allow you to access contentDocument and throw a cross-origin error however if frame is not loaded successfully then contentDocument will return a #document object

它不允许您访问contentDocument并抛出一个跨源错误,但是如果没有成功加载框架,那么contentDocument将返回一个#document对象

#9


1  

A really great method is use jQuery AJAX. The parent frame would look like this:

一个非常好的方法是使用jQuery AJAX。父框架看起来是这样的:

<iframe src="iframe_load.php" style="width: 100%; height: 100%;"></iframe>

The iframe_load.php file would load the jQuery library and a JavaScript that attempts to load the destination URL in an AJAX GET:

iframe_load。php文件将加载jQuery库和试图在AJAX GET中加载目标URL的JavaScript:

var the_url_to_load = "http://www.your-website.com" ;
$.ajax({
            type: "GET",
            url: the_url_to_load,
            data: "",
            success: function(data){
                // if can load inside iframe, load the URL
                location.href = the_url_to_load ;
            },
            statusCode: {
                500: function() {
                    alert( 'site has errors' ) ;
                }
            },
            error:function (xhr, ajaxOptions, thrownError){
                // if x-frame-options, site is down or web server is down
                alert( 'URL did not load due to x-frame-options' ) ;
            } });

IMPORTANT The destination must have contain the "Access-Control-Allow-Origin" header. Example in PHP:

重要的是,目标必须包含“访问控制允许的来源”头。在PHP示例:

HEADER( "Access-Control-Allow-Origin: *" ) ;