peli44
Posts: 6
Joined: Sun Feb 24, 2013 9:26 pm

Check networkconnection with Javascript

Sun Feb 24, 2013 9:32 pm

I am using a local webpage that starts when I boot the system. On that page I use Javascript.

The first thing I want to do is to check if the raspberry pi is connected to the LAN via Ethernet. I thought I could use this construction. I am using jQuery.

if (navigator.onLine == true)
{
connectStatus ="online";
}
else
{
connectStatus ="offline";
}

It works ok when I run it on my Mac but not on the Raspberry PI. On the Raspberry I always get the answer "online".

/Per

myminimonster
Posts: 33
Joined: Sun Dec 30, 2012 11:08 pm
Location: Midlands UK

Re: Check networkconnection with Javascript

Thu Feb 28, 2013 3:21 am

There is a mention here of a bug that linux always reports online.
https://developer.mozilla.org/en-US/doc ... tor.onLine


Maybe you could considering using a different language to do this.

I had a lot of stability issues with my pi so i set up a script that ran as a crontab and updated my db as to whether the pi could ping my router.
this way i was able to see when and if there was a pattern to my pi going offfline

Here is the python script i use.

Code: Select all

#!/usr/bin/python
# coding=UTF-8
import MySQLdb
import sys
import datetime
import subprocess
import shlex

command_line = "ping -c 1 192.168.0.1"
args = shlex.split(command_line)



try:
        db = MySQLdb.connect (host = "localhost", user = "xxxx", passwd = "xxxxx", db = "xxxxxxx")
#       print "connected"
except:
    print "Error "
    sys.exit (1)
now = datetime.datetime.now()
now1 = now.strftime("%Y-%m-%d %H:%M")
cur = db.cursor()
try:
        subprocess.check_call(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
        cur.execute("INSERT INTO tablename(row1, row2) VALUES(%s, 'ping alive')", now1)
        db.commit()
except:
        cur.execute("INSERT INTO tablename(row1, row2) VALUES(%s, 'ping dead')", now1)
        db.commit()
db.close ()






Adrian
Newbie

scrapheap
Posts: 20
Joined: Wed Feb 13, 2013 5:13 pm

Re: Check networkconnection with Javascript

Thu Feb 28, 2013 10:02 am

navigator.onLine is known to lie on some browsers. If it is is false then you are pretty sure to be offline, if it is true then you may or may not be online (depending on the browser). A sensible thing to do after discovering that navigator.onLine is true would be to make a http request to known web page and see if it fails.

Check out http://ednortonengineeringsociety.blogs ... tml-5.html for an example.

User avatar
katanac
Posts: 8
Joined: Fri Mar 08, 2013 3:28 am

Re: Check networkconnection with Javascript

Fri Mar 08, 2013 4:11 am

A better option would be to use node.js, and leverage the builtin os module.

Check: http://nodejs.org/api/os.html

os.networkInterfaces() would be quite useful for this circumstance.

Return to “Other programming languages”