iBooks test for an internet connection with HTML widget

922 views Asked by At

I created a widget in dashcode that embeds a YouTube video. I'd like to test for an interent connection first and alert the user. I embedded the YouTube widget into iBooks. I'm guessing at times some will not have an interent connection.


if I add:

 var online = window.navigator.onLine;
if (!online) {
alert("we are offline");
//console.log("We are offline!");
} else {
alert("we are online");
//console.log("We are online!");
}

And add that code to iBooks Author as a widget, the popup works fine, but there's no way to confirm the alert. Basically, it locks up the iBook. Any ideas?

1

There are 1 answers

0
Ben Evans On

I'm not sure about ibook dashboard, but I wrote a heartbeat checker for my web app that could be used to confirm http connection, perhaps it could do what you need... original post here

You call the code with a URL to check, a max ttl, and a callback. If the page has not responded by the end of the ttl (in milliseconds) the callback is called with null else you get the status and the request object.

function heartbeat(url, ttl, callback) {
    // Confirms active connection to server by custom URL response
    //
    if (!url) {
        url = "http://www.yourwebsitehere.com/yourpage?someheartbeatcall";
        // Replace with specific server heartbeat location and query string for cache busting
    }
    if (!ttl) {
        ttl = 1000; // Custom timeout in milliseconds
        // Replace with specific server heartbeat location and query string for cache busting
    }
    // Create the Ajax object
    var ajaxRequest;
    try{
            ajaxRequest = new XMLHttpRequest();
    }
    catch (e){
        // Internet Explorer Browsers
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch (e){
                // Unable to create
                callback(null);
                return;
            }
        }
    }
    // Set flag so only one pulse is recorded
    var called = false;
    // Make ajax call
    ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
            if (!called) {
                called = true;
                callback(ajaxRequest.status, ajaxRequest);
            }
        }
    }
    ajaxRequest.open("GET", url, true);
    ajaxRequest.send(null); 
    // Make ttl timeout call
    var ttlcatch = setTimeout(function(){
        if (!called) {
            called = true;
            callback(null);
        }
    }, ttl);
    return;
}

var foo = false;
heartbeat("http://www.google.com", 1000, function(pulse){alert(pulse);} )