JS Detect Offline? What Am I doing wrong - javascript

I'm a JS newb so I'm trying to figure out how to make this example from w3c to work in my WebApp that will run in a PhoneGap framework...
I'm sure this is easy, but when the event listener is triggered, it runs the attached function with the alert, problem is is it proceeds to excute everything after that again. So say I flip my iphone off, I'll get an alert then it will execute the next alert which says its online... Anywho... If any of you gys have any better ideas about executing a function like this let me know PhoneGap Cordova has two other methods as well.
<script>
<!--
window.addEventListener("offline", function(e) {alert("offline");})
window.addEventListener("online", function(e) {alert("online");})
if (navigator.onLine) {
alert('online')
//functions to run online
} else {
alert('offline');
//offline functions or through into loop
}
-->
</script>

You are missing a parameter in the addEventListener function.
For me this is working fine:
window.addEventListener("offline", function () {
console.log("Online status: " + navigator.onLine);
}, false);
window.addEventListener("online", function () {
console.log("Online status: " + navigator.onLine);
}, false);

try out this if(window.navigator.onLine) { alert('I am online');} I have just tested it in console and it works :)

Related

mac window load doesn't always fire

My load events do not always fire in safari or chrome on mac (safari version 7.0.5, chrome version 43.0.2357.124). It works fine in firefox and in any of my windows browsers.
window.addEventListener('load', function (){
alert("loaded js");
}, false);
$(window).bind("load", function() {
alert("loaded jquery");
});
Both functions fire or none of them does.
Does someone know what is happening here?
Thanks for help.
Since that JS is in a separate file, I can imagine that at the time it runs, the load event has already been fired.
You can detect this, however, using document.readyState (see also this question).
It has three possible values:
loading - parsing is still going on
interactive - parsing has finished, but resources are loading
complete - pasing has finished and resources have been loaded
I suggest you check whether document.readyState == 'complete' and run your code, otherwise register an event listener:
~function()
{
var loadJS = function()
{
alert("loaded js");
};
var loadJQ = function()
{
alert("loaded jquery");
};
if(document.readyState == 'complete')
{
loadJS();
loadJQ();
}
else
{
window.addEventListener('load', loadJS, false);
$(window).bind('load', loadJQ);
}
}();

How to know if the user is idle?

basically I want to run some code in jquery after the user has stopped doing anything in the browser like click,scroll. How to know if all functions have finished and jquery is not being busy (being run or used)
Basically run code only when the user is idle
If I am getting you right, this is what you were looking for
<script>
$(function(){
(function(seconds) {
var refresh,
intvrefresh = function() {
clearInterval(refresh);
refresh = setTimeout(function() {
alert('No activity from user 10 seconds, put your code here !');
}, seconds * 1000);
};
$(document).on('click keydown keyup mousemove', function() { intvrefresh() });
intvrefresh();
}(10));
});
</script>
Typically you'd wait until everything has loaded. This means that all elements have finished loading on the page (e.g. Images loaded in). There's nothing here to tell you that there's no JavaScript running in the background though.
$(window).load(function() {
// Do stuff
});
try {
var str =$('body').html();
} catch ( e ) {
alert('jquery not used');
}
Do something like this. jsfiddle
I just answered it here. See if it makes sense.
TLDR;
You can do it more elegantly with underscore and jquery-
$('body').on("click mousemove keyup", _.debounce(function(){
// your code here.
}, 1200000)) // 20 minutes debounce

JavaScript stops working when a call back function is added

I am experiencing a weird problem in my web page. JavaScript attached to a href gets called just fine and stops working if the called javascript function adds a statement with call-back function in it. Not even the alert placed as the very first statement in the JS func called from href fires in that case.
Here is an example:
Following works just fine.
when clicking on this link
refresh,
following js func gets called just fine and I see both alert messages indicating that getMyPosition() was executed. Note: at this time (i.e. when the js is seemingly working) the call-back function ("handleposition") is NOT defined but it does not raise any errors! weird in its own right :)
function getMyPosition() {
alert("it worked 1.");
if ( navigator.geolocation )
{
alert("it worked 2.");
navigator.geolocation.getCurrentPosition(handlePosition, handleError, {
enabledHighAccuracy: true,
maximumAge: 60000,
timeout: 30000
});
}
}
Now, if I add the following function in the script block, all stops working and it appears that the refresh link was even clicked on. Since everything else on the webpage (which contains JavaScript events etc attached to other items) keeps working fine, my assumption is that JavaSctipt on the page is working fine. Just this link stops calling the func defined on onClick event.
adding the following call-back function causes the behavior as if "refresh" link wasn't even clicked on:
function handlePosition(pos)
{
alert(pos.coords.latitude);
alert(pos.coords.longitude);
window.location.href = "/map?js=y&lat=pos.coords.latitude&lon=pos.coords.longitude";
}
Now if remove this function, the href link shown above will start working again and getMyPosition will get called and I see alert messages again!
I do not see any script errors on the page
Both IE 11 and Chrome as exhibiting this behavior.
I am on Windows 7 32bit machine.
Possibly the biggest problem was the missing error handler for the geolocation callback. Bringing up Chrome's debugger via F12 quickly revealed the problem.
Adding the error handler seemed to fix the problem, but on the way there I cleaned-up a few other things. Here's a fiddle showing it working
Here's how I'd code the link to work in all browsers:
refresh
And here's the revised JS code for handle position and the new handleError routine.
Note the "return false" added to your main function:
function getMyPosition() {
alert("it worked 1.");
if (navigator.geolocation) {
alert("it worked 2.");
navigator.geolocation.getCurrentPosition(handlePosition, handleError, {
enabledHighAccuracy: true,
maximumAge: 60000,
timeout: 30000
});
}
return false;
}
function handlePosition(pos) {
alert(pos.coords.latitude);
alert(pos.coords.longitude);
window.location.href = "/map?js=y&lat=" + pos.coords.latitude + "&lon=" + pos.coords.longitude;
}
function handleError(error) {
alert(error);
}
window.location.href = "/map?js=y&lat=pos.coords.latitude&lon=pos.coords.longitude";
should probably be:
window.location.href = "/map?js=y&lat=" + pos.coords.latitude + "&lon=" + pos.coords.longitude;
Put return false; in at the end of the getMyPosition function

JQuery document.ready vs Phonegap deviceready

I am making a phonegap application with jquery. I am confused whether I should wrap my entire code inside JQuery's $(document).ready() like
$(document).ready(function(){
//mycode
});
or inside the deviceready event of phonegap like
document.addEventListener("deviceready", function(){
//mycode
});
I am currently using document.ready but I think I may encounter problems if I try to access some Phonegap API methods inside document.ready.
Which is the best event to wrap my code in, document.ready or deviceready?
A key point in the answer is this line from the documentation of the deviceready event.
This event behaves differently from others in that any event handler registered after the event has been fired will have its callback function called immediately.
What this means is that you won't 'miss' the event if you add a listener after the event has been fired.
So, first move all the initialization code to the onDeviceReady function. Then first handle the document.ready. Within the document.ready if you determine that you are running in a browser, just call the onDeviceReady function, otherwise add the deviceready listener. This way when you are in the onDeviceReady function you are sure that all the needed 'ready's have happened.
$(document).ready(function() {
// are we running in native app or in a browser?
window.isphone = false;
if(document.URL.indexOf("http://") === -1
&& document.URL.indexOf("https://") === -1) {
window.isphone = true;
}
if( window.isphone ) {
document.addEventListener("deviceready", onDeviceReady, false);
} else {
onDeviceReady();
}
});
function onDeviceReady() {
// do everything here.
}
The isphone check works because in phonegap, the index.html is loaded using a file:/// url.
You should use the deviceready event to avoid funny things happening.
The docs state:
This is a very important event that every PhoneGap application should use.
PhoneGap consists of two code bases: native and JavaScript. While the native code is loading, a custom loading image is displayed. However, JavaScript is only loaded once the DOM loads. This means your web application could, potentially, call a PhoneGap JavaScript function before it is loaded.
The PhoneGap deviceready event fires once PhoneGap has fully loaded. After the device has fired, you can safely make calls to PhoneGap function.
Typically, you will want to attach an event listener with document.addEventListener once the HTML document's DOM has loaded.
Read the documentation here:http://docs.phonegap.com/en/1.0.0/phonegap_events_events.md.html
They are not the same.
jQuery.ready() is using:
document.addEventListener("DOMContentLoaded", yourCallbackFunction, false);
Source: https://code.jquery.com/jquery-3.1.1.js
Cordova/PhoneGap instructs you to use:
document.addEventListener("deviceready", yourCallbackFunction, false);
Source: https://cordova.apache.org/docs/en/latest/cordova/events/events.html
My suggestion is, that you put all the initialization code for your Cordova/PhoneGap plugins inside the callback function which is fired when the deviceready event occurs. Example:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
// Now safe to use device APIs
}
#Kinjal's answer really helped me get on track, but I had to fight a lot of issues with timing.
I use Cordova device ready event to read data files for my app, a few JSON packets which drive interface building and are loaded by default inside the www folder, but might eventually be downloaded from a server, to upgrade the application database.
I have found a lot of issues because the application data structures had not enough time to initialize before routing was started.
I wound up with this solution: initialize jQuery first, call the event handler of Cordova at the end of jQuery initialization, call the application startup routine at the end of the last processing in Cordova initialization.
All this nightmare started because I needed a way to read template files for Hogan.js and could not read them with the file protocol and a simple XHR.
Like this:
$(document).ready(function () {
...
// are we running in native app or in a browser?
window.isphone = false;
if (document.URL.indexOf('http://') === -1 && document.URL.indexOf('https://') === -1) {
window.isphone = true;
}
if (window.isphone) {
document.addEventListener('deviceready', onDeviceReady, false);
} else {
onDeviceReady();
}
});
function onDeviceReady() {
function readFromFile(fileName, cb) {
// see (https://www.neontribe.co.uk/cordova-file-plugin-examples/)
}
...
readFromFile(cordova.file.applicationDirectory + 'www/views/tappa.html', function (data) {
app.views.lastview = data;
app.start();
});
}
I am using PhoneGap Build cli-6.2.0 and when I test the procedure you suggested is doesn't do anything inside function onDeviceReady().
With older versions of PGB it works!
$(document).ready(function() {
window.isphone = false;
if (document.URL.indexOf("http://") === -1 && document.URL.indexOf("https://") === -1) { window.isphone = true }
if (window.isphone) { document.addEventListener("deviceready", this.onDeviceReady, false); } else { onDeviceReady(); }
});
function onDeviceReady() {
alert( window.isphone );
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
The one does not have to exclude the other. One simple example:
$(document).on('deviceready', function() {
console.log('event: device ready');
$(document).on('pause', function() {
console.log('event: pause');
});
$(document).on('resume', function() {
console.log('event: resume');
});
});

gBrowser.addEventListener: "load" event fired three times

I have installed the "hello world" dev example for Firefox extensions as described here:
http://blog.mozilla.com/addons/2009/01/28/how-to-develop-a-firefox-extension/
I have modified the anonymous function that gets passed to gBrowser.addEventListener:
gBrowser.addEventListener("load", function (event) {
var t = event.target;
alert("Content title: " + t.contentTitle);
}, false);
This function is getting called three times for every page load. When I click a link, it fires twice for the current (already loaded page) and once for the new page.
I have uninstalled all other addons (including Firebug) and still it fires 3 times. Does anyone know why this might be?
Thanks Richard
I would recommend you to do something like this:
window.addEventListener("load", function load() {
window.removeEventListener("load",load,false); //no longer needed
window.gBrowser.addEventListener('DOMContentLoaded', function load(event) {
your_addon.init_function(event);
}, false);
In my addon it works. :-)
Hope this helps.
MichaƂ

Categories