I looking for some pointer on how data is sent using a custom library that connects to a java server running as a websocket server.
The code im using to connect which is successful
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="b4j_ws.js"></script>
<script>
// connection to websocket
$( document ).ready(function() {
b4j_connect("/push/ws");
});
</script>
and this is my guess and how to send data using the library which at the moment is not correct, the message would be 'wwww' when sent successfully.
<script>
b4j_ws.send(JSON.stringify({"type":"data","data":"wwww"}));
</script>
These are frames i captured from the working example but it used a button where i want to just use jquery
{"type":"event","event":"btnsend_click","params":{"which":1,"target":"btnsend","pageX":31,"pageY":19,"metaKey":false}}
{"id":"#txt","method":"val","etype":"runmethodWithResult"}
{"type":"data","data":"wwww"}
the library which is b4j_ws.js in the above code.
//B4J WebSockets client library v0.9
/*jslint browser: true*/
/*global $, jQuery, WebSocket*/
/*jshint curly: false */
"use strict";
var b4j_ws;
var b4j_closeMessage = false;
//only called as a result of a server request that is waiting for result.
//this method should not be called in any other case.
function b4j_sendData(data) {
b4j_ws.send(JSON.stringify({type: "data", data: data}));
}
function b4j_raiseEvent(eventName, parameters) {
try {
if (b4j_ws.readyState !== 1) {
if (b4j_closeMessage === false) {
window.console.error("connection is closed.");
window.alert("Connection is closed. Please refresh the page to reconnect.");
b4j_closeMessage = true;
}
} else {
b4j_ws.send(JSON.stringify({type: "event", event: eventName, params: parameters}));
}
} catch (e) {
window.console.error(e);
}
}
function b4j_addEvent(selector, event, eventName, preventDefault) {
var obj = $(selector);
if (obj.length > 0) {
obj.on(event, function (e) {
if (preventDefault) {
e.preventDefault();
e.stopPropagation();
}
b4j_raiseEvent(eventName, {which: e.which, target: e.target.id, pageX: e.pageX, pageY: e.pageY, metaKey: e.metaKey});
});
}
}
function b4j_addAutomaticEvents(data) {
$.each(data, function (index, value) {
b4j_addEvent("#" + value.id, value.event, value.id + "_" + value.event, true);
});
}
function b4j_runFunction(func, params) {
return window[func].apply(null, params);
}
function b4j_eval(params, script) {
var f = new Function(script);
return f.apply(null, params);
}
function b4j_connect(absolutePath) {
if (typeof WebSocket === 'undefined') {
window.alert("WebSockets are not supported by your browser.");
return;
}
var l = window.location, fullpath;
fullpath = ((l.protocol === "https:") ? "wss://" : "ws://") + l.hostname + ":" + l.port + absolutePath;
b4j_ws = new WebSocket(fullpath);
b4j_ws.onmessage = function (event) {
var ed = JSON.parse(event.data);
if (ed.etype === "runmethod") {
$(ed.id)[ed.method].apply($(ed.id), ed.params);
} else if (ed.etype === "runmethodWithResult") {
b4j_sendData($(ed.id)[ed.method].apply($(ed.id), ed.params));
} else if (ed.etype === "setAutomaticEvents") {
b4j_addAutomaticEvents(ed.data);
} else if (ed.etype === "runFunction") {
b4j_runFunction(ed.prop, ed.value);
} else if (ed.etype === "runFunctionWithResult") {
b4j_sendData(b4j_runFunction(ed.prop, ed.value));
} else if (ed.etype === "eval") {
b4j_eval(ed.value, ed.prop);
} else if (ed.etype === "evalWithResult") {
b4j_sendData(b4j_eval(ed.value, ed.prop));
} else if (ed.etype === "alert") {
window.alert(ed.prop);
}
};
}
I change on the click method to a onload method in the java webserver and it worked!
Related
Given the following snippet of code
var empowerInstance = null;
function onClick_btnSendMessage() {
var childIFrame = window.document.getElementById("editorFrame");
if (!empowerInstance) {
empowerInstance = EditorAPI.getInstance(childIFrame.contentWindow, window.location.origin);
}
empowerInstance.document.hasChanged(hasChangedCallback);
}
function hasChangedCallback(returnValue) {
console.log("empowerInstance.document.hasChanged = " + returnValue.isDirty);
if (returnValue.success === true && returnValue.isDirty === true) {
empowerInstance.document.save(saveCallback);
}
}
function saveCallback(returnValue) {
console.log("empowerInstance.document.save = " + returnValue.success);
if (returnValue.success === false) {
console.log(returnValue.message);
}
}
window.addEventListener("DOMContentLoaded", function (event) {
console.log("DOM fully loaded and parsed");
if (typeof location.origin === "undefined")
window.location.origin = window.location.protocol + "//" + window.location.host;
document.getElementById("btnSendMessage").addEventListener("click", onClick_btnSendMessage);
});
Instead of wiring the button up , I'd like to fire the code from the activation of a Bootstrap tab event.
$('a[data-toggle="tab"]').on("shown.bs.tab", function (e) {
onClick_btnSendMessage(); // Naive way, as this does not wait
var target = $(e.target).attr("data-EditorUrl"); // activated tab
var childIFrame = $("#editorFrame");
childIFrame.attr("src", target);
});
So my question is "How do I wait on this function to complete before changing the source of childIFrame?".
empowerInstance.document.hasChanged(hasChangedCallback);
I conceptually understand the use of Promises and Callbacks, but writing one that functions correctly is a different story.
UPDATED
This version is refactored to eliminate the button handler, thus improving readability.
The usage is also important. When the page loads for the first time it is positioned on a tab. This tab is associated to a document that is hosted in an iFrame. If the user edits this document then tries to change tabs, I'd like to invoke the check for being dirty/save, then once saved, move to the next tab/document. There is also the case that switching between tabs/documents won't cause a save because the document is not dirty.
var empowerInstance = null;
function hasChangedCallback(returnValue) {
console.log("empowerInstance.document.hasChanged = " + returnValue.isDirty);
if (returnValue.success === true && returnValue.isDirty === true) {
empowerInstance.document.save(saveCallback);
}
}
function saveCallback(returnValue) {
console.log("empowerInstance.document.save = " + returnValue.success);
if (returnValue.success === false) {
console.log(returnValue.message);
}
}
$(function () {
if (typeof location.origin === "undefined") {
window.location.origin = window.location.protocol + "//" + window.location.host;
}
$('a[data-toggle="tab"]').on("shown.bs.tab", function (e) {
var childIFrame = $("#editorFrame");
if (!empowerInstance) {
empowerInstance = EditorAPI.getInstance(childIFrame[0].contentWindow, window.location.origin);
}
empowerInstance.document.hasChanged(hasChangedCallback);// Need to wait for completion
var target = $(e.target).attr("data-EditorUrl"); // activated tab
childIFrame.attr("src", target);
});
});
Thank you,
Stephen
I've refactored your code to show how this can be done using promises.
function onClick_btnSendMessage() {
var childIFrame = window.document.getElementById("editorFrame");
if (!empowerInstance) {
empowerInstance = EditorAPI.getInstance(childIFrame.contentWindow, window.location.origin);
}
var doc = empowerInstance.document;
return hasChanged(doc).then(function() { return save(doc) })
}
function hasChanged(doc) {
return new Promise(function(resolve, reject) {
doc.hasChanged(function(returnValue) {
if (returnValue.success === true && returnValue.isDirty === true) {
resolve(returnValue)
} else {
reject(returnValue)
}
})
})
}
function save(doc) {
return new Promise(function(resolve, reject) {
doc.save(function(returnValue) {
if (returnValue.success === false) {
console.log(returnValue.message);
reject(returnValue)
} else {
resolve(returnValue)
}
})
})
}
// ------
$('a[data-toggle="tab"]').on("shown.bs.tab", function(e) {
onClick_btnSendMessage().then(function() {
var target = $(e.target).attr("data-EditorUrl"); // activated tab
var childIFrame = $("#editorFrame");
childIFrame.attr("src", target);
}).catch(function(error) {
// handle the error
console.error('Error!', error)
})
});
You can use some higher order functions to do what you want. Instead of passing the hasChangedCallback and saveCallback directly to the empowerInstance.document methods, you'll instead invoke a function that returns those callbacks, but also passes along your own callback that you'll call once all the async operations have finally completed. Here's what it'll look like:
$('a[data-toggle="tab"]').on("shown.bs.tab", function (e) {
var target = $(e.target).attr("data-EditorUrl"); // activated tab
onClick_btnSendMessage(function () {
var childIFrame = $("#editorFrame");
childIFrame.attr("src", target);
});
});
function onClick_btnSendMessage(myCallback) {
var childIFrame = window.document.getElementById("editorFrame");
if (!empowerInstance) {
empowerInstance = EditorAPI.getInstance(childIFrame.contentWindow, window.location.origin);
}
empowerInstance.document.hasChanged(getHasChangedCallback(myCallback));
}
function getHasChangedCallback(myCallback) {
return function hasChangedCallback(returnValue, myCallback) {
console.log("empowerInstance.document.hasChanged = " + returnValue.isDirty);
if (returnValue.success === true && returnValue.isDirty === true) {
empowerInstance.document.save(getSaveCallback(myCallback));
}
}
}
function getSaveCallback(myCallback) {
return function saveCallback(returnValue) {
console.log("empowerInstance.document.save = " + returnValue.success);
if (returnValue.success === false) {
console.log(returnValue.message);
}
myCallback && myCallback(); // make sure myCallback isn't null before invoking
}
}
It's not exactly attractive, but it should get you what you want.
This function inside an object define the event handling for a xmlhttprequest object. As some browsers did not accept the addEventListener method, I did a test so if not, it will define onstatechange:
var reqEngatilhar = function(){
este.concluido = false;
timeoutId = setTimeout(reqTimeout, este.timeout);
if(este.Request.hasOwnProperty("onload")){
este.Request.addEventListener("error", reqErro, true);
este.Request.addEventListener("progress", reqMon, false);
este.Request.addEventListener("abort", reqAbort, false);
este.Request.addEventListener("load", reqFim, false);
console.log("$Http reqEngatilhar usando eventos...");
} else {
este.Request.onreadystatechange = function (e) { reqSwitch(e); };
console.log("$Http reqEngatilhar usando onreadystatechange...");
}
}
The "este" is "this" outside the function (var este = this;)
The "reqSwitch" will point to the right funcion. The problem is the test este.Request.hasOwnProperty("onload") works only in Safari. How can I make a cross-browser test to detect if the browser will work with addEventListener?
Just check whether the object has addEventListener set to a truthy value. By performing the check this way, you are not dependent on the prototype hierarchy that the browser uses behind the scenes. (As dandavis pointed out, it can be a problem.)
if (este.Request.addEventListener) {
este.Request.addEventListener("error", reqErro, true);
// etc...
} else {
este.Request.onreadystatechange = function (e) { reqSwitch(e); };
console.log("$Http reqEngatilhar usando onreadystatechange...");
}
If you are concerned about tools that could muck things and set addEventListener to funky values, you could do:
if (typeof este.Request.addEventListener === "function") {
TRY IT:
var util = {
getAttribute: function (dom, attr) {
if (dom.getAttribute !== undefined) {
return dom.getAttribute(attr);
} else if (dom[attr] !== undefined) {
return dom[attr];
} else {
return null;
}
},
addEvent: function (obj, evtName, func) {
//Primero revisar attributos si existe o no.
if (obj.addEventListener) {
obj.addEventListener(evtName, func, false);
} else if (obj.attachEvent) {
obj.attachEvent(evtName, func);
} else {
if (this.getAttribute("on" + evtName) !== undefined) {
obj["on" + evtName] = func;
} else {
obj[evtName] = func;
}
}
},
removeEvent: function (obj, evtName, func) {
if (obj.removeEventListener) {
obj.removeEventListener(evtName, func, false);
} else if (obj.detachEvent) {
obj.detachEvent(evtName, func);
} else {
if (this.getAttribute("on" + evtName) !== undefined) {
obj["on" + evtName] = null;
} else {
obj[evtName] = null;
}
}
},
getAjaxObject: function () {
var xhttp = null;
//XDomainRequest
if ("XMLHttpRequest" in window) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xhttp;
}
};
//START CODE HERE.
var xhr = util.getAjaxObject();
var isUpload = (xhr && ('upload' in xhr) && ('onprogress' in xhr.upload));
if (isUpload) {
util.addEvent(xhr, "progress", xhrEvt.onProgress());
util.addEvent(xhr, "loadstart", xhrEvt.onLoadStart);
util.addEvent(xhr, "abort", xhrEvt.onAbort);
}
util.addEvent(xhr, "readystatechange", xhrEvt.ajaxOnReadyState);
var xhrEvt = {
onProgress: function (e) {
if (e.lengthComputable) {
//Loaded bytes.
var cLoaded = e.loaded;
}
},
onLoadStart: function () {
},
onAbort: function () {
},
onReadyState: function () {
var state = xhr.readyState;
var httpStatus = xhr.status;
if (state === 4 && httpStatus === 200) {
//Completed success.
}
}
};
//CONTINUE YOUR CODE HERE.
This addEventListener polyfill might help you:
https://github.com/jonathantneal/EventListener
Save yourself the trouble of checking browser compatibility and let the polyfill handle that.
Try the older way to register events maybe ?
// Pass a function reference — do not add '()' after it, which would call the function!
el.onclick = modifyText;
// Using a function expression
element.onclick = function() {
// ... function logic ...
};
Check out this post to know more.
I currently have a chrome packaged app that we have also ported to iPad, but I want to make it install-able using node-webkit (nw.js) and I need to abstract the chrome packaged app API for use with chrome.fileSystem. The code I am currently using to save is as follows.
var downloadFile = function (readUrl, next) {
var xhr = new XMLHttpRequest();
xhr.open('GET', readUrl);
xhr.responseType = 'arraybuffer';
xhr.onload = function (e) {
if (this.status == 200) {
var response = this.response;
var params = {
type : 'saveFile',
suggestedName : fileNameNoExtension,
//my code will inject the extension but in this case i just put in txt
accepts : [{
extensions : ['.txt']
}
]
}
chrome.fileSystem.chooseEntry(params, function (writableFileEntry) {
debugger;
writableFileEntry.createWriter(function (writer) {
debugger;
writer.onwriteend = function (e) {
return next(null)
};
writer.onerror = function (e) {};
writer.write(new Blob([response], {
type : 'application/octet-stream'
}));
});
});
} else {
//alert
}
};
xhr.onprogress = function (evt) {
if (evt.lengthComputable) {
console.log('progress: ' + Math.round(evt.loaded * 100 / evt.total));
}
}
xhr.addEventListener("error", function () {
return next('error')
}, false);
xhr.addEventListener("abort", function () {
return next('abort')
}, false);
xhr.send();
}
I have created a file that I am calling interop.js I load this script into my index.html and it will handle all of the chrome packaged app API calls for fileStorage if it's a nw.js project. If it's a chrome packaged app, then chrome will handle it's own API.
//if process is undefined then it is not an nw.js project and we can ignore the rest of the code;
if (typeof process == 'undefined') {}
//this is a nw.js project, spoof the chrome packaged app API
else {
var fs = require('fs')
chrome = new function () {
var fileSystem = {
//callback return readableFileEntry, which has a
chooseEntry : function (params, callback) {
if (params.type == 'openFile') {
//open file choose
chooseFile(params, function (files) {
//this is technically an html5 "filelist" we need to turn it into an array if there is more
//than one, and just return the single file if there isn't
if (!files) {
return callback(null)
}
async.map(files, function (file, cb) {
//normally chrome provides a 'readablefileentry' that will only give you the file
//asynchronously using the file() function
file.file = function (next) {
return next(this);
}
cb(null, file)
}, function (err, files) {
if (files.length > 1) {
return callback(files);
} else {
return callback(files[0]);
}
})
})
} else if (params.type == 'saveFile') {
chooseFile(params, function (files) {
var file = files[0];
debugger;
file.createWriter = function (next) {
var writer = {
write : function (blob) {
debugger;
var reader = new FileReader()
reader.readAsArrayBuffer(blob)
reader.addEventListener('loadend', function (e) {
var binary = new Uint8Array(reader.result)
debugger;
fs.writeFile(file.path, new Buffer(binary), function (err) {
//if the on error and writeend has been defined then callback, otherwise throw the error and log success
if (err && writer.onerror) {
writer.onerror(err)
} else if (err) {
throw err
} else if (writer.onwriteend) {
writer.onwriteend()
} else {
console.log('file was written but no callback was defined')
}
})
});
}
}
return next(writer)
}
return callback(file)
})
}
function chooseFile(params, next) {
var fileHtml = '<input type="file"'
debugger;
if (params.acceptsMultiple)
fileHtml += ' multiple';
if (params.accepts && params.accepts.length > 0 && params.accepts[0].extensions) {
fileHtml += ' accept="'
for (var i = 0; i < params.accepts[0].extensions.length; i++) {
if (i != 0)
fileHtml += ','
fileHtml += '.' + params.accepts[0].extensions[i]
}
fileHtml += '"'
}
if (params.suggestedName) {
fileHtml += ' nwsaveas="' + params.suggestedName + '"'
}
fileHtml += '>'
var chooser = $(fileHtml);
chooser.change(function (evt) {
debugger;
return next(chooser[0].files)
});
chooser.click();
}
}
}
return {
fileSystem : fileSystem,
}
};
}
i have call the below function in my application
function workerCall() {
debugger;
if (typeof (Worker) !== "undefined") {
var worker = new Worker("Scripts/worker.js");
worker.onmessage = workerResultReceiver;
worker.onerror = workerErrorReceiver;
worker.postMessage({ 'username': Username });
function workerResultReceiver(e) {
$('.NotificationCount').html(e.data);
if (parseInt(e.data) != 0 && currentPage == "Alert") {
StateFlag = false;
$('.Notification').show();
$('.Drildown').each(function () {
var temp = this.id;
if ($('#' + temp).attr('expand') == "true") {
currentTab = temp;
StateFlag = true;
}
});
currentScrollPosition = $('body').scrollTop();
GetAlerts();
} else {
$('.Notification').hide();
}
}
function workerErrorReceiver(e) {
console.log("there was a problem with the WebWorker within " + e);
}
}
else {
}
}
the method will execute in IE,Chrome but when comes to Mozilla i got an error ReferenceError: workerResultReceiver is not defined.How can i resolve this error?
This happens because you are making reference to function that is not created yet. You need to put this:
worker.onmessage = workerResultReceiver;
worker.onerror = workerErrorReceiver;
Above
function workerErrorReceiver
line or at the end of the scope.
I am using the excellent onlinejs (https://github.com/PixelsCommander/OnlineJS) library for checking that my app has a live internet connection. However, I don't need it to fire regularly, but rather upon the manual calling of the main function.
I would like to modify this code so that it is not firing on a timer, and know the name of the function to call for manual firing, which assume is just getterSetter.
My previous attempts to modify the code below have broken the script as I'm no expert at JavaScript. I appreciate any help in adapting this very useful code.
function getterSetter(variableParent, variableName, getterFunction, setterFunction) {
if (Object.defineProperty) {
Object.defineProperty(variableParent, variableName, {
get: getterFunction,
set: setterFunction
});
}
else if (document.__defineGetter__) {
variableParent.__defineGetter__(variableName, getterFunction);
variableParent.__defineSetter__(variableName, setterFunction);
}
}
(function (w) {
w.onlinejs = w.onlinejs || {};
//Checks interval can be changed in runtime
w.onLineCheckTimeout = 5000;
//Use window.onLineURL incapsulated variable
w.onlinejs._onLineURL = "http://lascelles.us/wavestream/online.php";
w.onlinejs.setOnLineURL = function (newURL) {
w.onlinejs._onLineURL = newURL;
w.onlinejs.getStatusFromNavigatorOnLine();
}
w.onlinejs.getOnLineURL = function () {
return w.onlinejs._onLineURL;
}
getterSetter(w, 'onLineURL', w.onlinejs.getOnLineURL, w.onlinejs.setOnLineURL);
//Verification logic
w.onlinejs.setStatus = function (newStatus) {
w.onlinejs.fireHandlerDependOnStatus(newStatus);
w.onLine = newStatus;
}
w.onlinejs.fireHandlerDependOnStatus = function (newStatus) {
if (newStatus === true && w.onLineHandler !== undefined && (w.onLine !== true || w.onlinejs.handlerFired === false)) {
w.onLineHandler();
}
if (newStatus === false && w.offLineHandler !== undefined && (w.onLine !== false || w.onlinejs.handlerFired === false)) {
w.offLineHandler();
}
w.onlinejs.handlerFired = true;
};
w.onlinejs.startCheck = function () {
setInterval("window.onlinejs.logic.checkConnectionWithRequest(true)", w.onLineCheckTimeout);
}
w.onlinejs.stopCheck = function () {
clearInterval("window.onlinejs.logic.checkConnectionWithRequest(true)", w.onLineCheckTimeout);
}
w.checkOnLine = function () {
w.onlinejs.logic.checkConnectionWithRequest(false);
}
w.onlinejs.getOnLineCheckURL = function () {
return w.onlinejs._onLineURL + '?' + Date.now();
}
w.onlinejs.getStatusFromNavigatorOnLine = function () {
if (w.navigator.onLine !== undefined) {
w.onlinejs.setStatus(w.navigator.onLine);
} else {
w.onlinejs.setStatus(true);
}
}
//Network transport layer
var xmlhttp = new XMLHttpRequest();
w.onlinejs.isXMLHttp = function () {
return "withCredentials" in xmlhttp;
}
w.onlinejs.isXDomain = function () {
return typeof XDomainRequest != "undefined";
}
//For IE we use XDomainRequest and sometimes it uses a bit different logic, so adding decorator for this
w.onlinejs.XDomainLogic = {
init: function () {
xmlhttp = new XDomainRequest();
xmlhttp.onerror = function () {
xmlhttp.status = 404;
w.onlinejs.processXmlhttpStatus();
}
xmlhttp.ontimeout = function () {
xmlhttp.status = 404;
w.onlinejs.processXmlhttpStatus();
}
},
onInternetAsyncStatus: function () {
try {
xmlhttp.status = 200;
w.onlinejs.processXmlhttpStatus();
} catch (err) {
w.onlinejs.setStatus(false);
}
},
checkConnectionWithRequest: function (async) {
xmlhttp.onload = w.onlinejs.logic.onInternetAsyncStatus;
var url = w.onlinejs.getOnLineCheckURL();
xmlhttp.open("GET", url);
w.onlinejs.tryToSend(xmlhttp);
}
}
//Another case for decoration is XMLHttpRequest
w.onlinejs.XMLHttpLogic = {
init: function () {
},
onInternetAsyncStatus: function () {
if (xmlhttp.readyState === 4) {
try {
w.onlinejs.processXmlhttpStatus();
} catch (err) {
w.onlinejs.setStatus(false);
}
}
},
checkConnectionWithRequest: function (async) {
if (async) {
xmlhttp.onreadystatechange = w.onlinejs.logic.onInternetAsyncStatus;
} else {
xmlhttp.onreadystatechange = undefined;
}
var url = w.onlinejs.getOnLineCheckURL();
xmlhttp.open("HEAD", url, async);
w.onlinejs.tryToSend(xmlhttp);
if (async === false) {
w.onlinejs.processXmlhttpStatus();
return w.onLine;
}
}
}
if (w.onlinejs.isXDomain()) {
w.onlinejs.logic = w.onlinejs.XDomainLogic;
} else {
w.onlinejs.logic = w.onlinejs.XMLHttpLogic;
}
w.onlinejs.processXmlhttpStatus = function () {
var tempOnLine = w.onlinejs.verifyStatus(xmlhttp.status);
w.onlinejs.setStatus(tempOnLine);
}
w.onlinejs.verifyStatus = function (status) {
return status === 200;
}
w.onlinejs.tryToSend = function (xmlhttprequest) {
try {
xmlhttprequest.send();
} catch(e) {
w.onlinejs.setStatus(false);
}
}
//Events handling
w.onlinejs.addEvent = function (obj, type, callback) {
if (window.attachEvent) {
obj.attachEvent('on' + type, callback);
} else {
obj.addEventListener(type, callback);
}
}
w.onlinejs.addEvent(w, 'load', function () {
w.onlinejs.fireHandlerDependOnStatus(w.onLine);
});
w.onlinejs.addEvent(w, 'online', function () {
window.onlinejs.logic.checkConnectionWithRequest(true);
})
w.onlinejs.addEvent(w, 'offline', function () {
window.onlinejs.logic.checkConnectionWithRequest(true);
})
w.onlinejs.getStatusFromNavigatorOnLine();
w.onlinejs.logic.init();
w.checkOnLine();
w.onlinejs.startCheck();
w.onlinejs.handlerFired = false;
})(window);
Looking at the source, I believe you can simply call onlinejs.logic.checkConnectionWithRequest(false) to get the status synchronously. This function will return either true or false.
PS: I am sure there are better libraries for this task out there, I really do not like the way it's written and clearly, the author doesn't know JS very well. E.g., the following code taken from the library makes no sense at all.
w.onlinejs.stopCheck = function () {
clearInterval("window.onlinejs.logic.checkConnectionWithRequest(true)", w.onLineCheckTimeout);
}