checking network connections using cordova - javascript

I'm trying to check my connections via cordova, the logic that I'm trying to do, is:
if network connected give "greetings" alert, else replace elements of the main view.
my difficult is to if connection ok, just give greetings message. someone could check my code to help me do to?
regards
function net(){
var theNet = navigator.connection.type;
var status = {};
status[Connection.NONE] = 'Sem acesso';
status[Connection.UNKNOWN] = 'Sem conexão';
status[Connection.WIFI] = 'Conexão wireless';
status[Connection.CELL] = 'Rede de operadora';
status[Connection.UNDEFINED] = 'Sem definição';
//alert(status[suaNet]);
var result = "<p style='text-align:center'><img style='height:20em;width:20em;' src='img/icon-dove-1024x934.png'></p>";
var blank = "<ul class='nav navbar-nav'><li style='texto-menu'><a href='#'>Nothing here</a></li></ul>";
if(Connection.NONE || Connection.UNKNOWN === false)
{
BootstrapDialog.alert("hi");
}
else if(Connection.NONE || Connection.UNKNOWN === true){
document.getElementById('div-inteira').innerHTML = result;
document.getElementById('menu-barra-hamburguer').innerHTML = blank;
}
else{
console.log("doest works");
}

are you doing this after device.ready function ?
Try consoling the network type before you check for the connection's. And make sure your using the correct implementation of the plugin.

Related

"jQuery requires a window with a document" on jquery $get

Why does this error happen when it try to use jquery? This code was working before but I don't even know what did I do for this error to happen. I tried to search about it and nothing I looked up makes sense or it's about this jsdom or whatever that I don't use. Exception is thrown on the 1st line in the try catch. That's the only error I could get from the browser debugger:
function DisplayName() {
if (Page_ClientValidate()) {
try {
$get("lblNameShow").html = $get("<%= txtNome.ClientID %>").value;
$get("lblDataAdmissaoShow").innerHTML = document.getElementById("datepicker").value;
var ddlD = document.getElementById("<%= ddlDepartamento.ClientID%>");
var strDDLDepart = ddlD.options[ddlD.selectedIndex].text;
$get("lblDepartamentoShow").innerHTML = strDDLDepart;
var ddlF = document.getElementById("<%= ddlFuncao.ClientID%>");
var strDDLFunc = ddlF.options[ddlF.selectedIndex].text;
$get("lblFuncaoShow").innerHTML = strDDLFunc;
//get valor radio button
var rstTel = $('#<%=rblTelemovel.ClientID %> input[type=radio]:checked').val();
if (rstTel == 0)
$get("lblTelemovelShow").innerHTML = "Não"
else
$get("lblTelemovelShow").innerHTML = "Sim"
var message = "";
var checkBoxList = document.getElementById("<%=cblAppAlternativas.ClientID%>");
var checkBoxes = checkBoxList.getElementsByTagName("INPUT");
for (var i = 0; i < checkBoxes.length; i++) {
if (checkBoxes[i].checked) {
var value = checkBoxes[i].value;
var text = checkBoxes[i].parentNode.getElementsByTagName("LABEL")[0].innerHTML;
message += value + "-" + text + ",";
}
}
//alert(message);
$get("lblAcessoShow").innerHTML = message;
$get("lblObShow").innerHTML = $get("<%= txtObservacoes.ClientID %>").value;
} catch (err) {
$get("demo").innerHTML = err.message;
}
$('#NewColabModal').modal('show')
}
return false;
}
EDIT
The code works if I remove the get from the jquery selector, but the strange thing is the code was working before. I can't find any info about using $get in jquery to select elements so I'm not sure about it if it's a plugin. This code was already implemented in the project I'm working on so I have no idea which plugin uses $get.
on the original project these are the only references on it
<link rel="stylesheet" type="text/css" href="jquery-ui-1.12.1.custom/jquery-ui.css" />
<script src="jquery-ui-1.12.1.custom/external/jquery/jquery.js"></script>
<script src="jquery-ui-1.12.1.custom/jquery-ui.js"></script>
<script type="text/javascript" src="NOTY/js/noty/packaged/jquery.noty.packaged.js"></script>
EDIT 2
So I was using a try catch to catch the error but I was doing it in the wrong way since I'm still new to javascript. The exception I got is that $get is not defined. So rather than asking where $get comes from, how do I define a variable in jquery like $get?

Get IFrame's name from WebBrowser2 using VC++ COM

VARIANT varindex,varresult;
VariantInit(&varindex);
VariantInit(&varresult);
varindex.vt = VT_I4;
varresult.vt = VT_DISPATCH;
long lFrameNum = 0;
CComPtr<IHTMLFramesCollection2> pFramesCollection;
hr = m_spDoc->get_frames(&pFramesCollection); //CComPtr<IHTMLDocument2> m_spDoc
if(FAILED(hr))
{
return false;
}
hr = pFramesCollection->get_length(&lFrameNum);
if(FAILED(hr))
{
return false;
}
for(int i=0; i<lFrameNum; i++)
{
varindex.lVal = i;
if(pFramesCollection->item(&varindex, &varresult) == S_OK)
{
IDispatch *pDispatch;
pDispatch = varresult.pdispVal;
CComQIPtr< IHTMLFrameBase > spFrameBase(pDispatch);
if(!spFrameBase) return false; //failed here, E_NOINTERFACE
}
}
The codes here shows how to enum frames in a webpage, and get its name. I get the IDispatch of each iframe successfully, but when I tried to get IHTMLFrameBase (IID_IHTMLFrameBase), it failed with the error E_NOINTERFACE.
I am not familiar with COM, what did I do wrong? Help me please, thanks in advance.
Though, I didn't get the frame name directly, but I figured out how to get The IHTMLDocument2* of that specific frame. And Then, I can do something to the frame, like call its js functions etc. The codes are like below:
VARIANT varindex,varresult;
VariantInit(&varindex);
VariantInit(&varresult);
varindex.vt = VT_BSTR;
varindex.bstrVal = "Frame Name"; //the specific frame name
pFramesCollection->item(&varindex,&varresult);
IHTMLWindow2* pFrameWindow;
varresult.pdispVal->QueryInterface(IID_IHTMLWindow2, (void **)&pFrameWindow);
IHTMLDocument2* pDoc;
pFrameWindow->get_document(&pDoc);
//do something ...

Java Applet is undefined

I have this jzebra applet that I need to do some client side ticket printing.
This is the applets html definition:
<applet id="jzebra" name="jzebra" code="jzebra.PrintApplet.class" archive="../../../../../../web/org.openbravo.howtos/lib/jzebra.jar"
width="10px" height="10px">
The function I call in the form button is this:
function printDocument() {
var applet = document.jzebra;
var frm = document.frmMain;
var url = frm.elements["inpftpOBDir"].value;
var file ="0.txt";
var archivo = url + "/" + file;
if (applet != null) {
var printname = frm.elements["inpPrinterName"].value;
var indice = frm.inpPrinterSelected.selectedIndex;
var printselected = frm.inpPrinterSelected.options[indice].text;
alert(printname);
alert(printselected);
if(printselected == ""){
// printname = "zebra"
//alert('Default : ' + printname);
applet.findPrinter(printname);
monitorFinding();
} else {
//alert('Selected : ' + printselected);
applet.findPrinter(printname);
monitorFinding();
}
alert('File : ' + archivo);
// applet.findPrinter(printname);
applet.appendFile(archivo);
// Send characters/raw commands to printer
applet.print();
alert('The document was sent to the printer.');
}
}
I checked the console and there is a definition of applet, but when it reaches applet.findPrinter(printname), just explodes because applet.findPrinter is not a function.
Has anyone faced this struggle before? I have seen that there is a little gray square in the top left corner of my page. When I hover on it, it displays "undefined".
I finally came up with a very complex solution, having to use jnlp. I will post my code later for references, if anyone else find similar problems.

GeoIP Redirect Loop - How to solve it?

I want to redirect my users to different languages/subfolders based on their IP address. To do this I use the JavaScript GeoIP API from MaxMind.
The problem: The english speaking people should stay at mydomain.com and not go to mydomain.com/en/. But when I redirect to mydomain.com the GeoIP script runs again which creates an infinite loop.
Here is my code (in index.html for mydomain.com):
<script language="JavaScript" src="http://j.maxmind.com/app/geoip.js"></script>
<script language="JavaScript">
var country = geoip_country_code();
if(country == "FR")
{
window.location = "http://mydomain.com/fr/"
}
else
{
window.location = "http://mydomain.com/";
}
</script>
In other posts I read about setting a cookie, but I wasn't able to do it in a way that solves the problem (and it would still create a loop when the user doesn't accept cookies, on mobile for example).
Another solution could be to redirect to mydomain.com/en/ and delete the /en/ folder in the URL via htaccess, but I wasn't able to get this done either.
An example of how I want it to work would be waze.com (it seems like they have the english version in the /en/ folder, but delete it from the URL).
So if anybody is able to help, I would be very grateful. Thanks a lot!
EDIT: I solved the problem myself. It's very simple: Just use the root directory for the english page and change function to "else {null;}" :-)
Your problem is not with geoip but with your code.
Try this:
var country = geoip_country_code();
var currentLocation = String(window.location);
//if geoip is equal FR and window.location is different "http://mydomain.com/fr/"
if(country === "FR" && currentLocation.indexOf("http://mydomain.com/fr/")!==0)
{
window.location = "http://mydomain.com/fr/"
}
//if geoip is different FR and window.location is equal "http://mydomain.com/fr/"
else if(currentLocation.indexOf("http://mydomain.com/fr/")===0)
{
window.location = "http://mydomain.com/";
}
To detect using multiple languages ​​simply edit the following variables:
var defaultsLang are the languages ​​that are supported by the main root (site.com/)
var languages languages supported by sub-pages (site.com/fr/, site.com/es/, etc.)
See code (not tested):
(function(){
var defaultsLang = ["en-us","en"];
var languages = {
"fr": true, //enable french pages
"pt": false, //tmp disable portuguese pages
"es": true //enable spanish pages
};
var country = geoip_country_code().toLowerCase(),
currentLocation = String(window.location),
detectCurrent = function(){
var a = currentLocation.replace(/^(http|https)[:]\/\//, "");
var b = a.split("\/");
b = b[1].toLowerCase();
a = null;
return b.length<5 && (/^[a-z\-]+$/).test(b) ? b : false;
};
var currentLang = detectCurrent();
defaultsLang = "|"+defaultsLang.join("|")+"|";
if(currentLang!==country && typeof languages[country] !=="undefined" && languages[country]!==false){
window.location = "http://mydomain.com/" + country + "/";
} else if(
defaultsLang.indexOf("|" + currentLang + "|")===-1 && //current page is not the same as default languague(s)
defaultsLang.indexOf("|" + country + "|")!==-1 && //geoip is in the list of default language(s)
currentLang!==false
){
window.location = "http://mydomain.com/";
}
})();

How do i solve these issues?

I wrote simplest extension as an exercise in JS coding. This extension checks if some user (of certain social network) is online, and then outputs his/her small image, name and online status in notification alert. It checks profile page every 2 minutes via (setTimeout), but when user becomes "online", i set setTimeout to 45 minutes.(to avoid online alerts every 2 minutes).
It works, but not exactly as i expected. I have 2 issues:
1)When certain user is online and i change user id (via options page) to check another one, it doesnt happen because it waits 45 or less minutes. i tried the following code (in options.html), but it doesnt help.
2)When i change users, image output doesnt work correctly!! It outputs image of previous user!!
How do i fix these problems??
Thanks!
options.html
<script>
onload = function() {
if (localStorage.id){
document.getElementById("identifier").value = localStorage.id;
}
else {
var el = document.createElement("div");
el.innerHTML = "Enter ID!!";
document.getElementsByTagName("body")[0].appendChild(el);
}
};
function onch(){
localStorage.id = document.getElementById("identifier").value;
var bg = chrome.extension.getBackgroundPage();
if(bg.id1){
clearTimeout(bg.id1);
bg.getdata();
}
}
</script>
<body>
<h1>
</h1>
<form id="options">
<h2>Settings</h2>
<label><input type='text' id ='identifier' value='' onchange="onch()"> Enter ID </label>
</form>
</body>
</html>
backg.html
<script type="text/javascript">
var domurl = "http://www.xxxxxxxxxxxxxx.xxx/id";
var txt;
var id1;
var id2;
var imgarres = [];
var imgarr = [];
var imgels = [];
function getdata() {
if (id1){clearTimeout(id1);}
if (id2){clearTimeout(id2);}
var url = getUrl();
var xhr = new XMLHttpRequest();
xhr.open('GET',url, true);
xhr.setRequestHeader('Cache-Control', 'no-cache');
xhr.setRequestHeader('Pragma', 'no-cache');
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
txt = xhr.responseText;
var r = txt.indexOf('<b class="fl_r">Online</b>');
var el = document.createElement("div");
el.innerHTML = txt;
var n = imgprocess(el,url);
var nam = el.getElementsByTagName("title")[0].innerHTML;
if (r != -1) {
var notification = webkitNotifications.createNotification(n, nam, 'online!!' );
notification.show();
var id1 = setTimeout(getdata, 60000*45);
}
else {
var id2 = setTimeout(getdata, 60000*2);
}
}}
xhr.send();
}
function imgprocess(text,url){
imgels = text.getElementsByTagName("IMG");
for (var i=0;i< imgels.length;i++){
if (imgels[i].src.indexOf(parse(url)) != -1){
imgarr.push(imgels[i]);
}
}
for (var p=0; p< imgarr.length; p++){
if (imgarr[p].parentNode.nodeName=="A"){
imgarres.push(imgarr[p]);
}
}
var z = imgarres[0].src;
return z;
}
function getUrl(){
if (localStorage.id){
var ur = domurl + localStorage.id;
return ur;
}
else {
var notif = webkitNotifications.createNotification(null, 'blah,blah,blah', 'Enter ID in options!!' );
notif.show();
getdata();
}
}
function init() {
getdata();
}
</script>
</head>
<body onload="init();">
</body>
</html>
In options instead of clearTimeout(bg.id1); try bg.clearTimeout(bg.id1);
For image problem looks like you never clean imgarres array, only adding elements to it and then taking the first one.
PS. You code is very hard to read, maybe if you made it well formatted and didn't use cryptic variable names you would be able to find bugs easier.
UPDATE
I think I know what the problem is. When you are setting the timeout you are using local scope variable because of var keyword, so your id1 is visible only inside this function and global id1 is still undefined. So instead of:
var id1 = setTimeout(getdata, 60000*45);
try:
id1 = setTimeout(getdata, 60000*45);
Because of this if(bg.id1){} inside options is never executed.
(bg.clearTimeout(bg.id1); should work after that, but it is not needed as you are clearing the timeout inside getdata() anyway)

Categories