检测 iframe 中的连接问题

Detect connection issues in iframe

本文关键字:连接 问题 iframe 检测      更新时间:2023-09-26

这个问题与一个HTML文件有关,该文件在不同的iframe标签中调用不同的页面。 有没有办法,可能使用 JavaScript,检查页面是否存在连接问题?如果是这样,请尝试重新加载此帧,直到建立连接。

更清楚一点,如果您查看以下链接(http://tvgl.barzalou.com)(即使内容是法语,您也会注意到页面的不同部分如何正确加载,并且通常正确加载)。 但是偶尔,在周末,与网络的轻微连接问题到达,出于某种原因,框架发出这个荒谬的灰色/浅灰色图标,说存在连接问题。 当然,当手动重新加载页面时,框架会恢复活力。

请检查更新的代码,该代码将在达到最大尝试次数后检查并重新加载 iframe...

<script language="javascript">
 var attempts = 0;
 var maxattempt = 10;
 var intid=0;
 $(function()
 {
     intid = setInterval(function() 
     {
        $("iframe").each(function()
        {
           if(iframeHasContent($(this))) 
           {
              //iframe has been successfully loaded
           }
           if(attempts < maxattempt)
           {
             attempts++;
           }
           else
           {
             clearInterval(intid);
             checkAndReloadIFrames();
           }
        })
     },1000);
 })
 function iframeHasContent($iframe)
 { 
     if($iframe.contents().find("html body").children() > 0)
     {
        return true; 
     }
     return false;
 }   
 
 function checkAndReloadIFrames()
 {
     $("iframe").each(function()
        {
            //If the iframe is not loaded, reload the iframe by reapplying the current src attribute
           if(!iframeHasContent($(this))) 
           {
               //reload iframes if not loaded 
               var $iframe = $(this);
               var src = $iframe.attr("src");
               //code to prevent cache request and reload url
               src += "?_" + new Date().getTime();
               $iframe.attr("src",src);
           }
        });
 }
 </script>

您可以安排一个代码来检查 iframe 是否正确加载

考虑一个示例

<script language="javascript">
     var attempts = 0;
     var maxattempt = 10;
     var intid=0;
     $(function()
     {
         intid = setInterval(function() 
         {
            
            $("iframe").each(function()
            {
               if(iframeHasContent($(this))) 
               {
                  //iframe has been successfully loaded
               }
               
               if(attempts < maxattempt)
               {
                 attempts++;
               }
               else
               {
                 clearInterval(intid);
               }
            })
         },1000);
     })
     function iframeHasContent($iframe)
     { 
         if($iframe.contents().find("html body").children() > 0)
         {
            return true; 
         }
         return false;
     }   
</script>

这个简单的代码片段将检查文档中的 iframe 是否已正确加载。它将尝试 10 次尝试,然后中止检查。

当检查中止时,您可以为每个 iframe 调用 iframeHasContent() 以列出尚未加载的 iframe,并在需要时重新加载它们。