A simple question, how i can check if cordova is properly accessible and working in my html index file in android.
I tried searching for some syntax or code that can confirm but alas...
There are some functions that I am not able to access. Like navigator.connection.type gives me that type not defined of null..
So I am wondering if there is any way to check.
Thanks..
EDIT 1
$(document).one('pageinit', function(event) {
registerElementEvents();
validateFields();
// Check Internet Connection
checkConnection();
});
function checkConnection() {
//alert(window.top.navigator);
var objects = window.top.navigator;
for(var key in objects) {
var value = objects[key];
//alert(value);
}
if( !navigator.network )
{
// set the parent windows navigator network object to the child window
navigator.network = window.top.navigator.network;
}
// return the type of connection found
return ( (navigator.network.connection.type === "none" || navigator.network.connection.type === null ||
navigator.network.connection.type === "unknown" ) ? false : true );
}
There are lots of way to check
you can use the alert("your message"); so that you get a popup window in the function that
you want to work
Another way is using console.log("TESTING"); which will generate a log file. you can trace the log file too
for your nxt question regarding the connection type you can see and use this https://github.com/apache/cordova-plugin-network-information/blob/dev/doc/index.md
So reviewing the code it looks like the issue is that there is no check for the deviceready event.
Try something like this:
HTML:
<body onload="onLoad">
JS:
function onLoad() {
document.addEventListener('deviceready', deviceReady, false);
}
function deviceReady() {
registerElementEvents();
validateFields();
// Check Internet Connection
checkConnection();
}
I make use of a boolean value. When it is true, PhoneGap is propperly loaded.
// device ready
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
window.deviceReady = true;
}
Related
In my flutter app I have html inside a webview and some javascript with jquery attached. I want to trigger different actions depending on if a list item receives 'tap' or 'taphold'. I'm using jquery-mobile 1.5.0-rc1.
My javascript is as follows:
$('div.board').on('taphold tap', 'div.thread, div.thread-special', function(event) {
console.log('event');
var $item = $(this); // The item that was clicked or held
var scope = $item.data('itemscope'); // No numbered IDs! You can find everything about the item
// etc.
var type = event.type;
if (type === 'tap') {
console.log('tap');
} else if (type === 'taphold') {
console.log('taphold');
}
});
When I tap, I can see a 'tap' in the console. When I taphold, nothing at all happens or appears on the console. Any idea why?
I try to pick a contact with cordova plugin contacts, but I still have a bug. My button #pickContact opens correctly the activity where I can tap on a contact. But when I tap on one, nothing happens. When I go back to my page, I have the error message OPERATION_CANCELLED_ERROR (code 6).
I really don't understand where is the problem. I run my app on Android Marshmallow. I thought about a permission problem, but my app can find correctly contacts with navigator.contacts.find, but not with navigator.contacts.pickContact
Here is my code :
function pickContact() {
navigator.contacts.pickContact(function(contact){
alert('ok !');
},function(err){
alert('bug !' + err);
console.log('Error: ' + err);
});
}
var app = {
// Application Constructor
initialize: function() {
this.onDeviceReady();
if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/)) {
document.addEventListener("deviceready", this.onDeviceReady, false);
} else {
this.onDeviceReady();
}
},
onDeviceReady: function() {
$("#pickContact").click(pickContact);
},
// Update DOM on a Received Event
receivedEvent: function(id) {
}
};
app.initialize();
Thanks for your help !
As per the reference doc of contacts plugin your selected contact will set into JSON.stringify(contact) you can alert it to see which contacts are selected (I have used this plugin but I don't need this function to pick any single contact so not sure if there is any done button or not) then press done or ok button, which will redirect you to your another function where you can get that contacts or fulfill your next requirements.
function pickContact() {
navigator.contacts.pickContact(function(contact){
alert(JSON.stringify(contact));
//This is added by me, on done button click or single selection
setContacts(contact);
},function(err){
alert('bug !' + err);
console.log('Error: ' + err);
});
}
//This is added by me
function setContacts(ct)
{
alert(JSON.stringify(ct));
$("#contactlist").append(ct);
//or
var getData = JSON.parse(ct);
if(getData.length > 1)
{
for(i=0;i<getData.length;i++)
{
$("#contactlist").append(getData[i]);
}
}
}
Let me know if I am wrong or right.
Thanks a lot for your answer. Unfortunately , your code doesn't works for me, but I found what to do :
When pickcontact opens your native app "contacts", your cordova app is removed on background. On android, that means that you loose the state of your app, and so you have a bug. To solve the problem, you need to add onresume event on your js file, like this :
var app = {
// Application Constructor
initialize: function() {
this.onDeviceReady();
if (navigator.userAgent.match(/(iPhone|iPod|iPad|Android|BlackBerry)/)) {
document.addEventListener("deviceready", this.onDeviceReady, false);
} else {
this.onDeviceReady();
}
},
onDeviceReady: function() {
$("#pickContact").click(pickContact);
},
onResume: function(resumeEvent) {
//alert('onResume');
},
// Update DOM on a Received Event
receivedEvent: function(id) {
}
};
app.initialize();
After that, you can retrieve your picked contact with a function like this :
function pickContact() {
navigator.contacts.pickContact(function(contact){
$("#divTest").append('<p>The following contact has been selected:' + JSON.stringify(contact));
},function(err){
alert('bug !' + err);
console.log('Error: ' + err);
});
}
So, like everytime in programming, when you know the answer, that's easy. But when you don't know, you loose hours and hours...
I hope that will help someone.
I need to check if user is connected to the internet. My code works very well on browser but fails in android phone.
In app.js, I have the following code:
$rootScope.online = navigator.onLine;
$window.addEventListener("offline", function () {
console.log("called offline")
$rootScope.$apply(function() {
$rootScope.online = false;
});
}, false);
$window.addEventListener("online", function () {
console.log("called online")
$rootScope.$apply(function() {
$rootScope.online = true;
});
}, false);
In app, The events are never really fired and navigator.onLine always returns true? How do I fix this?
I've an app built with cordova and InAppBrowser. I'm trying to show a "loading spinner" in every page.
In iOS it's working well on every page I load, but Android fails.
On iOS I just edited self.spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] this line in CDVInappBrowser.m and works.
Does Android have a similar feature ?
Here is my code:
// Cordova is ready
function onDeviceReady() {
var ref = window.open("http://m.estadao.com.br/?load-all=true", "_blank", "location=no", "toolbar=no", "closebuttoncaption=a", "EnableViewPortScale=no");
navigator.notification.activityStart("Loading", "Loading...");
setTimeout(function(){
navigator.notification.activityStop();
}, 5000);
}
Check this plugin:
https://github.com/Paldom/SpinnerDialog
Working for me in Android. You should use this method to show a spinner with title and message:
window.plugins.spinnerDialog.show("Loading","Loading...");
Your code would be:
function onDeviceReady() {
var ref = window.open("http://m.estadao.com.br/?load-all=true", "_blank", "location=no", "toolbar=no", "closebuttoncaption=a", "EnableViewPortScale=no");
window.plugins.spinnerDialog.show("Loading","Loading...");
setTimeout(function(){
window.plugins.spinnerDialog.hide();
}, 5000);
}
Resvolvi dessa forma
//window.open Example
// Wait for device API libraries to load
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
// external url
// var ref = window.open(encodeURI('http://mfsom.com.br/'), '_blank', 'location=no','toolbar=no');
//relative document
ref = window.open('http://mfsom.com.br/','_self',',location=no');
ref.addEventListener('loadstart', loadstartCallback);
ref.addEventListener('loadstop', loadstopCallback);
ref.addEventListener('loadloaderror', loaderrorCallback);
ref.addEventListener('exit', exitCallback);
function loadstartCallback(event) {
showSpinnerDialog();
}
function loadstopCallback(event) {
hideSpinnerDialog();
}
function loaderrorCallback(error) {
console.log('Erro ao carregar: ' + error.message)
}
function exitCallback() {
console.log('O navegador está fechado...')
}
function showSpinnerDialog() {
navigator.notification.activityStart("Carregando..");
//$.mobile.loading("show");
}
function hideSpinnerDialog() {
navigator.notification.activityStop();
//$.mobile.loading("hide");
}
// Handle the Cordova pause and resume events
document.addEventListener( 'pause', onPause.bind( this ), false );
document.addEventListener( 'resume', onResume.bind( this ), false );
// TODO: Cordova has been loaded. Perform any initialization that requires Cordova here.
};
As both the answers here use the activityStop() which is deprecated, use your own spinner which you use in your app to prevent InAppBrowser's blank opening screen
Open the InAppBrowser in using hidden=yes option and later in loadstop event listener show the InAppBrowser. Till then you can show your custom loader
var ref = window.open("http://m.estadao.com.br/?load-all=true", "_blank", "location=no,toolbar=no,closebuttoncaption=a,EnableViewPortScale=no,hidden=yes");
ref.addEventListener('loadstart', function() {
showLoader();//`showLoader()` is your own loader function to show loader within your app
});
ref.addEventListener('loadstop', function() {
ref.show();
hideLoader();//`hideLoader()` is your own loader function to hide loader within your app
});
I've develop an Android app with phonegap, my app need to swicthing on the toggle button, then user can close the app and running it in background service. My problem is when I close the app and back to the app again, its back to the initial state with toggle button off.
So, My question is how can we saving/restroring app state on android and phonegap?
I've read this Save & restoring WebView in an embedded PhoneGap app , but I still don't understand about restoreFromPreferences() and saveToPreferences(out) Can anyone help?
*Sorry for bad english
As #geet said, localStorage is what you need to store datas and retrieve them later.
According to Phonegap website, localstorage provides access to a W3C Storage interface. You can read about it here : http://dev.w3.org/html5/webstorage/#the-localstorage-attribute.
To save a toggle button position this is what I do :
<script>
function onDeviceReady() {
// Set togglebutton to false default
var togglebutton = window.localStorage.getItem("togglebutton");
if (togglebutton==null) window.localStorage.setItem("togglebutton", 'false');
// Set default state
if (window.localStorage.getItem("togglebutton")=='true') {
$('#onoffswitch').attr("checked", "checked");
}
// Switch onoffswitch event
$('#onoffswitch').on('change', function(){
if ($(this).prop('checked')) {
window.localStorage.setItem("togglebutton", 'true');
} else {
window.localStorage.setItem("togglebutton", 'false');
}
});
}
</script>
Make sure in your HTML that your toggle element (form me a checkbox) isn't checked by default :
<input type="checkbox" name="onoffswitch" id="onoffswitch">
About Pause and Resume, you can perform actions when these events are called. To do this :
<script>
document.addEventListener("resume", yourCallbackFunction, false);
document.addEventListener("pause", yourCallbackFunction, false);
</script>
U can store any data in localstorage in your JS.
e.g
To save value of var username.
localStorage.setItem("username",edited_name);
To retrive
var getUser=localStorage.getItem("username");
hope it will help to u!!
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
document.addEventListener("pause", onPause, false);
function onDeviceReady() {
var pageNow = document.getElementsByTagName(body);
var currentPage = JSON.stringify(pageNow);
localStorage.setItem("uiState", currentPage);
}
function onPause() {
//retrieve info here
var pageShow = document.getElementsByTagName(body);
let techStack = localStorage.getItem("uiState");
// JSON.parse(techStack); //unnecessary because the parser will detect HTML
pageShow.innerHTML(techStack);
}
}
you can get the current state of the UI in any element, just use a different selector.
will update this answer to incorporate SQL later