if there is no internet connection, hide iframe

2019-06-05 19:52发布

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);
});

I am not able to hide iframe if there is no internet connection. I don't know what's wrong here. Thanks.

2条回答
狗以群分
2楼-- · 2019-06-05 20:26

navigator.onLine tells you if the browser is in "offline" mode or not.

It does not actually check if you can reach the net, as you probably think.

(To do this, you could try to ping Google.com with ajax, or do some similar trick)

查看更多
戒情不戒烟
3楼-- · 2019-06-05 20:31

You could do an ajax request with type:'jsonp' and timeout:3000 (which is three seconds) to the same page you want to include via the frame.

$.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
       }
    }
});

However, you will always get syntax error, because content of that page is not a script. But browsers usually are able to restore after such errors. UPD. Just tried it with your url, it works.

查看更多
登录 后发表回答