Here is my code at the minute:
Using phonegap 2.9
<head>
</head>
<body>
<script charset="utf-8" src="js/cordova.js"></script>
<script>
document.addEventListener("deviceready", onDeviceReady, false);
document.addEventListener("online", onOnline, false);
document.addEventListener("offline", onOffline, false);
// PhoneGap is loaded and it is now safe to make calls PhoneGap methods
//
function onDeviceReady() {
console.log("Device Ready");
}
// Handle the online event
//
function onOnline() {
document.location = 'http://app.dadad.com';
}
function onOffline() {
console.log("Offline");
}
</script>
</body>
However right now I just get a white screen whether i'm connected or not. Eventually what I would like is to display some html when the user is not connected.
So in conclusion:
Would like to fix the function as it is not working
Would like to show html when not connected.
The Online/Offline events do not fire onload. They are there for when you are in app (complete load) and then lose or gain connection. I have gotten around this by doing an initial connection check on load, like this:
function checkConnetcion() {
var networkState = navigator.connection.type;
var states = {};
states[Connection.UNKNOWN] = false;
states[Connection.ETHERNET] = true;
states[Connection.WIFI] = true;
states[Connection.CELL_2G] = true;
states[Connection.CELL_3G] = true;
states[Connection.CELL_4G] = true;
states[Connection.CELL] = true;
states[Connection.NONE] = false;
var connectionStatus = states[networkState];
if(connectionStatus) {
//Do something if connected
}
else{
//Do something if not connected
}
}
Then add this your onready function:
// PhoneGap is loaded and it is now safe to make calls PhoneGap methods
//
function onDeviceReady() {
console.log("Device Ready");
checkConnetcion();
}
You can make use of Jquery ajax and send a dummy request before sending actual request. If you get and Error Code as '0' it means there is no internet connectivity.
$.ajax({
url: 'TestUrl',
type: 'GET',
success: function (data) {
// Go ahead with you request
},
error: function (x, y, z) {
if (x.status == 0) {
alert("Please connect to the internet");
}
else{
alert("Other Error Occured")
}
}
});
Secondly you can also make you of HTML 5 navigator
var condition = navigator.onLine ? "ONLINE" : "OFFLINE";
But it will show ONLINE when WIFI doesn't provide Internet connection.
Cordova connection object will also show WIFI if there is no internet connection
Related
I am using cordova 3.5.0 to develop my phonegap application . In that i want to check internet connectivity before web service calls . So i added network status plugin by using the command cordova plugin add org.apache.cordova.network-information . Plugin installed successfully in my application .
After Adding the plugins i added 2 EventListener's one for online and another for offline.
var app = {
// Application Constructor
initialize: function() {
console.log('App initializing...');
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
//This is to allow testing in desktop browser where there is no device ready event
if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/)) {
document.addEventListener('deviceready', this.onDeviceReady, false);
document.addEventListener("offline", onOffline, false);
document.addEventListener("online", onOnline, false);
} else {
this.onDeviceReady();
}
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicity call 'app.receivedEvent(...);'
onDeviceReady: function() {
StatusBar.overlaysWebView(false);
app.receivedEvent('deviceready');
},
onOnline:function(){
console.log("Online");
}.
onOffline: function(){
console.log("Offline");
},
// Update DOM on a Received Event
receivedEvent: function(id) {
require(['router'], function(Router){
Router.getInstance();
console.log('Backbone callback...');
});
}
};
So i used another method to check online status as mentioned in Phonegap documentation
function checkConnection() {
var networkState = navigator.network.connection.type;
var states = {};
states[Connection.UNKNOWN] = 'Unknown connection';
states[Connection.ETHERNET] = 'Ethernet connection';
states[Connection.WIFI] = 'WiFi connection';
states[Connection.CELL_2G] = 'Cell 2G connection';
states[Connection.CELL_3G] = 'Cell 3G connection';
states[Connection.CELL_4G] = 'Cell 4G connection';
states[Connection.NONE] = 'No network connection';
alert('Connection type: ' + states[networkState]);
}
which is always returning the mode am connected to internet for e.g "WiFi connection" . Though i changed my disconnected my internet connection .
Help me resolving this issue .
I had the same problem: the online/offline event was not firing, and sometimes when it went offline, the app crashed...
THE SOLUTION:
- The appropriate permission tag must bem IMMEDIATELY after the tag , in the AndroidManifest.xml file... it may appear ridiculous, but otherwise the event was not firing.
In the end, your file will look like:
<manifest android:hardwareAccelerated="true" android:versionCode="10000" android:versionName="1.0.0" android:windowSoftInputMode="adjustPan" package="br.com.burkard.app" xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<supports-screens android:anyDensity="true" android:largeScreens="true" android:normalScreens="true" android:resizeable="true" android:smallScreens="true" android:xlargeScreens="true" />
Scope.
document.addEventListener("offline", this.onOffline, false);
document.addEventListener("online", this.onOnline, false);
I avoid using the network types, as I found they do not work consistently on all platforms.
Instead I use:
isOnline = function() {
try {
if (!navigator.onLine){
return false;
} else {
return true;
}
}
catch(e) {
alert('An error has occurred: '+e.message);
}
};
I would do to things.
First add the online and offline eventlisteners only in the onDeviceReady function,
Second, add scope to the onOffline and onOnline method calls in the event listeners.
Something like this:
if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/)) {
document.addEventListener('deviceready', this.onDeviceReady, false);
} else {
this.onDeviceReady();
}
},
onDeviceReady: function() {
StatusBar.overlaysWebView(false);
app.receivedEvent('deviceready');
document.addEventListener("offline", app.onOffline, false);
document.addEventListener("online", app.onOnline, false);
},
onOnline:function(){
console.log("Online");
}.
onOffline: function(){
console.log("Offline");
},
If, for example, i will that fileReader must return a content value of file, i get back only empty string. Global variable for me impossible to use, only local. Is it possible?
What do i wrong?
Edit:
function onDeviceReady() {
console.log("==> DEVICE READY");
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onFSSuccess, fileErrorMSG);
}
function onFSSuccess(fs) {
fileSystem = fs;
}
function readlocalFile(fileName) {
var core = "";
fileSystem.root.getFile(fileName, {create: false}, function(f) {
f.file(function(e) {
var reader = new FileReader();
reader.onloadend = function(evt) {
var res = $.parseJSON(evt.target.result);
core = res;
};
reader.readAsText(e);
});//f.file()
}, fileErrorMSG);
return core;
}
function loadDefaultCore(url) {
if (url) {
var myCore = readlocalFile(url);
console.log(myCore); // **output - empty string!!!!!!!!**
} else {
alert('can not load default core');
}
}
Thanks!
Well there a bunch of things to consider. In brief:
First, to read a file you need to get the file system.
Second, on success you need to get the file entry using the file system.
Third, on success read the file using the file entry.
The three have to be chained via the functions callbacks.
You are getting empty as you file is not being read.
I follow the chain an after the onFSSuccess function the chain is broken, the readLocalFile function is not being called, just add it after you assign your file system to the fileSystem variable which I assume is a global variable. Or call your function loadDefaultCore, I am not sure which one you really want to call first.
It will help you if you add more console log messages in each function so you can actually debug the problem easily.
Also, did you have your document even listener attached to the device ready function?
Any messages, errors warnings in the console?
From the phonegap file api, follow this and you will be safe. Check the doc for the phonegap version you are working on.
http://docs.phonegap.com/en/2.4.0/cordova_file_file.md.html#FileReader
<script type="text/javascript" charset="utf-8">
// Wait for Cordova to load //function onLoad() { document.addEventListener("deviceready", onDeviceReady, false); }
// Cordova is ready //function onDeviceReady() { window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, gotFS, fail); }
function gotFS(fileSystem) { fileSystem.root.getFile("readme.txt", null, gotFileEntry, fail); }
function gotFileEntry(fileEntry) { fileEntry.file(gotFile, fail); }
function gotFile(file){ readDataUrl(file); readAsText(file); }
function readDataUrl(file) { var reader = new FileReader(); reader.onloadend = function(evt) { console.log("Read as data URL"); console.log(evt.target.result); }; reader.readAsDataURL(file); }
function readAsText(file) { var reader = new FileReader(); reader.onloadend = function(evt) { console.log("Read as text"); console.log(evt.target.result); }; reader.readAsText(file); }
function fail(evt) { console.log(evt.target.error.code); }
</script>
I am creating a call center application ,and when a call come to twilio client on chrome browser it ask for permission to allow use of speaker and mic .When second call comes I have to allow it for two times and if third call come I have to allow three times and so on.
and in firfox browser ,when I acccept call second time it automatically disconnect and give error of mediastream.
Please suggest me where I am wrong and how to solve this problem.
Below is the javascript of twilio client,If need some more information please let me know
<script
type="text/javascript">
//var
token
=callaction();
var
connection=null;
var
content;
$(document).ready(function(){
$('#hangupcallbutton').hide();
$.post('cleanify?action=createcall',
function(data){
content=
data;
Twilio.Device.setup(content,
{
debug:
true}
);
}
);
Twilio.Device.ready(function
(device)
{
$("#log").text("Ready");
}
);
Twilio.Device.error(function
(error)
{
$("#log").text("Error:
"
+
error.message);
}
);
Twilio.Device.connect(function
(conn)
{
//alert("connect
handler");
$("#log").text("Successfully
established
call");
connection
=
conn;
}
);
Twilio.Device.disconnect(function
(conn)
{
//alert("in
disconnect");
$("#callbutton").html('Call');
$("#callbutton").removeClass("btn-danger
").addClass("btn-success");
//
$("#callbutton").toggleClass('btn-danger
btn-success');
$("#log").text("Call
ended");
$('#RejectCallButton').show();
$('#acceptcallbutton').show();
$('#hangupcallbutton').hide();
$('#myModal').modal('hide');
}
);
Twilio.Device.incoming(function
(conn)
{
//
alert("in
incomming");
connection
=
conn;
$("#log").text("aa
rahi
h
call");
$('#myModal').modal('show');
$('#incomingnumber').html(conn.parameters.From);
$('#RejectCallButton').click(function()
{
connection.reject();
}
);
$('#acceptcallbutton').click(function()
{
connection.accept();
$('#RejectCallButton').hide();
$('#acceptcallbutton').hide();
$('#hangupcallbutton').show();
}
);
$('#hangupcallbutton').click(function()
{
$('#RejectCallButton').show();
$('#acceptcallbutton').show();
$('#hangupcallbutton').hide();
connection.disconnect();
}
);
//
accept
the
incoming
connection
and
start
two-way
audio
}
);
Twilio.Device.cancel(
function
(conn)
{
//alert("in
cancel");
connection
=
conn;
$('#myModal').modal('hide');
}
);
$.each(['0','1','2','3','4','5','6','7','8','9','star','pound'],
function(index,
value)
{
$('#button'
+
value).click(function(){
//alert("hello");
if(connection)
{
if
(value=='star')
connection.sendDigits('*')
else
if
(value=='pound')
connection.sendDigits('#')
else
connection.sendDigits(value)
return
false;
}
}
);
}
);
//
Do
something
with
c
alert(content);
}
);
function
callhandle(){
if($("#callbutton").html().trim()
==
'Call'){
$("#callbutton").html('HangUp');
$("#callbutton").removeClass("btn-success").addClass("btn-danger");
//
$("#callbutton").toggleClass('btn-success
btn-danger');
call();
}
else
if($("#callbutton").html().trim()
==
'HangUp'){
hangup();
$("#callbutton").html('Call');
$("#callbutton").removeClass("btn-danger").addClass("btn-success");
//
$("#callbutton").toggleClass('btn-danger
btn-success');
}
}
function
call()
{
//
get
the
phone
number
to
connect
the
call
to
//
get
the
phone
number
to
connect
the
call
to
//
alert(
$("#selectOutgoing").val());
params
=
{"PhoneNumber":
$('.dialnumber').val(),"From":
$("#selectOutgoing").val(),"isclient":
"true"}
;
Twilio.Device.connect(params);
}
function
hangup()
{
Twilio.Device.disconnectAll();
}
</script>
From my experience, Chrome will only store those settings over HTTPS. Over HTPP Chrome will not store the settings thus it will prompt for the permissions every time
It might happen after a call before initialize twilio when you get another call . So , you must initialize first .
I am building a firefox addon that loads javascript at every page load. I'm using progress listener function I found on this page: https://developer.mozilla.org/en/Code_snippets/Progress_Listeners
My problem is that the code seems to execute to early before the page is fully loaded which causes my script to not run. Here is my code.
var PageLoad = {
browser: null,
domain: null,
oldURL: null,
init: function() {
gBrowser.addProgressListener(urlBarListener,Components.interfaces.nsIWebProgress.NOTIFY_LOCATION);
},
uninit: function() {
gBrowser.removeProgressListener(urlBarListener);
},
processNewURL: function(aURI) {
//if (aURI.spec == this.oldURL)
//return;
MyObject.function();
this.oldURL = aURI.spec;
}
};
var urlBarListener = {
locChange: false,
QueryInterface: function(aIID) {
if (aIID.equals(Components.interfaces.nsIWebProgressListener) ||
aIID.equals(Components.interfaces.nsISupportsWeakReference) ||
aIID.equals(Components.interfaces.nsISupports))
return this;
throw Components.results.NS_NOINTERFACE;
},
onLocationChange: function(aProgress, aRequest, aURI) {
PageLoad.processNewURL(aURI);
},
onStateChange: function(aWebProgress, aRequest, aFlag, aStatus) {},
onProgressChange: function(a, b, c, d, e, f) {},
onStatusChange: function(a, b, c, d) {},
onSecurityChange: function(a, b, c) {}
};
window.addEventListener("load",
function() {
PageLoad.init()
}, false);
var MyObject = {
function : function() {
var script = PageLoad.browser.createElement('script');
script.src = 'url_to_script.js';
PageLoad.browser.getElementsByTagName('head')[0].appendChild(script);
}
};
With this code I get this error message on the console:
PageLoad.browser.getElementByTagName("head")[0] is undefined
If I add a timeout then the script does work intermittently but if the page loads slow I get the same error, here's what works sometimes setTimeout(MyObject.function, 1000);
I need a more reliable way of making sure it's executing the script after the page is loaded.
Unrelated, and it doesn't seem to cause any problems but I also see this error message:
gBrowser.addProgressListener was called with a second argument, which is not supported. See bug 608628.
If you want to load javascript at every page load - the best way is subscribing to DOMContentLoaded event:
var MyObject = {
processDOMContentLoaded: function(doc) {
var script = doc.createElement('script');
script.src = 'url_to_script.js';
script.type = 'text/javascript';
doc.getElementsByTagName('head')[0].appendChild(script);
}
};
window.addEventListener('load', function() {
var appcontent = document.getElementById('appcontent');
if(appcontent != null) {
appcontent.addEventListener('DOMContentLoaded', function(event) {
var doc = event.originalTarget;
if(doc instanceof HTMLDocument) {
MyObject.processDOMContentLoaded(doc);
}
}, true);
}
}, false);
Have not tested, but should work.
You are using onLocationChange method - but if you look at how the browser behaves, the location in the address bar changes as soon as a connection with the server is established. You should look at state changes instead:
onStateChange: function(aWebProgress, aRequest, aFlag, aStatus)
{
if ((aFlag & Components.interfaces.nsIWebProgressListener.STATE_STOP) &&
(aFlag & Components.interfaces.nsIWebProgressListener.STATE_IS_WINDOW))
{
// A window finished loading
PageLoad.windowLoaded(aWebProgress.DOMWindow);
}
},
Note that the window that finished loading is explicitly passed to PageLoad.windowLoaded() - you will be receiving notifications from different tabs and you cannot assume that the notification comes from the foreground tab.
As to the warning you are getting, just leave out the second parameter in the call to gBrowser.addProgressListener():
gBrowser.addProgressListener(urlBarListener);
tabbrowser.addProgressListener() only accepts one parameter, unlike nsIWebProgress.addProgressListener() which has a second parameter.
Actually its a great question.
You should use event listener, but carefully, because if you trigger for every page load its can trigger you more than one time (in the worst case about dozens of times).
So how you can do that?
window.addEventListener("load", function load(event){
window.removeEventListener("load", load, false); //remove listener, no longer needed
myExtension.init();
},false);
var myExtension = {
init: function() {
var appcontent = document.getElementById("appcontent"); // browser
if(appcontent){
appcontent.addEventListener("DOMContentLoaded", myExtension.onPageLoad, true);
}
},
onPageLoad: function(aEvent) {
var doc = aEvent.originalTarget; // doc is document that triggered the event
var win = doc.defaultView; // win is the window for the doc
if (doc.nodeName != "#document") return;
if (win != win.top) return;
if (win.frameElement) return;
alert("the main page has been loaded");
},
};
get notice that we check for the type of the trigger every pageload triggering to prevent multi load.
The answers that were provided were acceptable but I found yet another solution that works perfectly.
var PageLoad = {
init: function() {
if(gBrowser) gBrowser.addEventListener("DOMContentLoaded", this.onPageLoad, false);
},
onPageLoad: function(aEvent) {
var doc = aEvent.originalTarget; // doc is document that triggered the event
var win = doc.defaultView; // win is the window for the doc
if (doc.nodeName != "#document") return;
if (win != win.top) return;
if (win.frameElement) return;
MyAddon.function();
}
}
window.addEventListener("load", function load(event){
window.removeEventListener("load", load, false); //remove listener, no longer needed
PageLoad.init();
},false);
Basically I am using ChildBrowser on iOS, it works almost perfectly. The problem is the onLocationChange, onClose and onOpenExternal don't work and for the life of me I can't figure out why.
Any help would be much appreciated
<script type="text/javascript" charset="utf-8">
var cb;
function onBodyLoad()
{
document.addEventListener("deviceready",onDeviceReady,false);
}
/* PhoneGap has been initialized and is ready to roll */
function onDeviceReady()
{
console.log("Device Ready");
cb = ChildBrowser.install();
}
function openChildBrowser(url)
{
console.log("New Url"+url);
try {
cb.showWebPage(url);
cb.onLocationChange = function(loc){ root.locChanged(loc); };
cb.onClose = function(){root.onCloseBrowser()};
cb.onOpenExternal = function(){root.onOpenExternal();};
}
catch (err)
{
alert(err);
}
}
function onCloseBrowser()
{
console.log("closed");
alert("In index.html child browser closed");
}
function locChanged(loc)
{
console.log("new loc:"+loc);
childBrowser.close();
alert("In index.html new loc = " + loc);
}
function onOpenExternal()
{
console.log("new loc:");
alert("In index.html onOpenExternal");
}
</script>
I have tried window.plugins.childBrowser.onLocationChange ect.
take out the root.onlocationChange, no need to have that.
Encapsulate the locChanged, onCloseBrowser, onOpenExternal into a main function to make correct calls because childbrowser when it´s opened doesn't have the scope of locChanged
for example:
var facebook = function() {
locChanged = funciton() {
//your code here
}
return {
"init": init,
"locChanged": locChanged,
"onCloseBrowser": onCloseBrowser,
"onOpenExternal": onOpenExternal
}
}();