如果没有互联网连接,请隐藏iframe

if there is no internet connection, hide iframe

本文关键字:隐藏 iframe 互联网 连接 如果没有      更新时间:2023-09-26

iframe:

<iframe id="iframe" title="Environment Canada Weather" src="" allowtransparency="false" frameborder="0" height="170"></iframe>

jquery:

$( document ).ready(function() {
    window.setInterval(function(){
        if (navigator.onLine) {
            //$("#iframe").show();
            $("#iframe").attr("src", "http://weather.gc.ca/wxlink/wxlink.html?cityCode=on-143&amp;lang=e");
        }
        else{
            $("#iframe").hide();
        }
    }, 5000);
});

如果没有互联网连接,我无法隐藏iframe。我不知道这里出了什么问题。谢谢

navigator.onLine告诉浏览器是否处于"脱机"模式。

它实际上并没有像你想象的那样检查你是否能触网。

(要做到这一点,你可以尝试用ajax ping Google.com,或者做一些类似的技巧)

您可以使用type:'jsonp'timeout:3000(即三秒)通过框架对要包含的同一页面进行ajax请求。

$.ajax({
    type : "GET",
    url : "http://weather.gc.ca/wxlink/wxlink.html?cityCode=on-143&amp;lang=e",
    timeout : 3000,
    dataType : "jsonp",
    crossDomain : true,
    success : function (response, textS, xhr) {
        // never get here
    },
    error : function (xmlHttpRequest, textStatus, errorThrown) {
       if (textStatus === 'timeout') {
          // not reachable
       } else {
          // reachable
       }
    }
});

然而,您总是会遇到语法错误,因为该页面的内容不是脚本。但浏览器通常能够在出现此类错误后进行恢复。UPD。只是用你的网址试了一下,就行了。