I am overriding my device back button per the documentation that I attach event listener to backbutton with argument of false after the deviceready event.
I have done so like this:
// Smart App object
define([
'routes',
'cordova',
'angular',
'angularRoute',
'angularResource',
'angularTouch',
'config',
'controllers',
'services',
'directives',
'helpers'
], function(appRoute) {
var oApp = {
_app: {},
init: function() {
console.log('init');
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
console.log('ok device ready');
document.addEventListener('backbutton', function() {
console.error('deviceback start');
angular.element('.ng-scope').scope().back();
console.error('deviceback end');
}, false);
// ...
}
// ...
I have worked crazily to figure out why hitting the device button is not triggering this backbutton event i attached, i dont even see the console.error messages in the console. I am testing on Android right now I haven't tested on any of the other Phone OS'es yet.
The console.log('ok device ready') does fire and my app works properly, the device backbutton is overridden in that its default functionality is not taking place, however as stated, my function is not taking place either.
I read other stackoverflow topcis and they said the Cordova version landed a fix, but my Cordova version is much after theirs, my .cordova/config.json file tells me:
{
"lib": {
"www": {
"id": "com.tigoenergy.smart",
"version": "3.5.0"
}
}
}
It is 3.5 and then my info.txt tells me it is 5.0.0:
Node version: v0.10.25
Cordova version: 5.0.0
Config.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<!-- config.xml reference: https://build.phonegap.com/docs/config-xml -->
<widget xmlns = "http://www.w3.org/ns/widgets"
xmlns:gap = "http://phonegap.com/ns/1.0"
Does anyone have any ideas?
Try using the normal way of using cordova events.
// device APIs are available
//
function onDeviceReady() {
// Register the event listener
document.addEventListener("backbutton", onBackKeyDown, false);
}
// Handle the back button
//
function onBackKeyDown() {
//Add your back button implementation.
}
official documentation here
Modified code
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<title>Tigo SMART Installation</title>
<script type="text/javascript" src="apps/installation/js/jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="apps/installation/js/index.js"></script>
<script type="text/javascript" src="apps/installation/js/fastclick.min.js"></script>
<script type="text/javascript" src="apps/installation/js/sha512.js"></script>
<script type="text/javascript" src="bower_components/uri.js/src/URI.min.js"></script>
<script type="text/javascript" src="js/extlogin.js"></script>
<link rel="stylesheet" href="css/app.css">
<link rel="stylesheet" type="text/css" href="apps/installation/css/index.css" />
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
//mycode
console.log('ok loaded');
document.addEventListener("deviceready", onDeviceReady, false);
});
// Wait for device API libraries to load
//
/*function onLoad() {
console.warn('ok loaded')
document.addEventListener("deviceready", onDeviceReady, false);
}
*/
// device APIs are available
//
function onDeviceReady() {
// Register the event listener
console.log('ok device ready');
document.addEventListener("backbutton", onBackKeyDown, false);
}
// Handle the back button
//
function onBackKeyDown() {
console.log('ok backey downed');
}
</script>
</head>
<body>
<div ng-view></div>
<script data-main="bin/SmartApp" src="bower_components/requirejs/require.min.js"></script>
<img style="opacity:0;visibility:hidden;" class="loader" src="img/loader.gif" />
</body>
</html>
Few reference links here and here
The issue was I was importing cordova.js in an iframe even though it was already in the parent window scope. I didn't know it would break it and thought I had to import cordova.js in the iframe. Removing the from the iframe fixed it.
Try This
$(document).ready(function () {
document.addEventListener("backbutton", onBackKeyDown, false);
});
function onBackKeyDown() {
alert('ok backey downed');
}
Make sure these files are link in your page
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="scripts/platformOverrides.js"></script>
<script type="text/javascript" src="scripts/index.js"></script>
Related
Can anyone explain to me how to get the device's IMEI number from Phonegap?
I am using the IMEI plugin in my app it is not showing anything.
To install, I have tried both:
phonegap plugin add https://github.com/zho/phonegap-imeiplugin.git
-- OR --
cordova plugin add imeiplugin
Example Usage:
window.plugins.imeiplugin.getImei(callback);
function callback(imei) {
console.log("My Android IMEI :" + imei);
I want the output to be displayed when user opens the app, but it is not showing.
here is the solution that how can you use imeiplugin
Index.html
<!DOCTYPE html>
<html>
<body>
<h1 id="demo"></h1>
<script type="text/javascript" src="cordova.js"></script>
<script src="js/index.js"></script>
<script> app.initialize(); </script>
</body>
</html>
Index.js
var app = {
// Application Constructor
initialize: function () {
app.bindEvents();
},
bindEvents: function () {
document.addEventListener('deviceready', app.onDeviceReady, false);
},
onDeviceReady: function () {
window.plugins.imeiplugin.getImei(callback);
}
};
function callback(imei) {
var element=document.getElementById("demo");
element.value=imei;
}
There is something wrong with the plugin you provided it showing an error like imeiplugin is unefined at window.plugins.imeiplugin.getImei(callback);
so i tried with the below and its worked for me
cordova plugin add org.hygieiasoft.cordova.uid
and call the finction on device ready
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady() {
console.log(cordova.plugins.uid.IMEI);
}
check this for more info
I begin my adventure with write unit tests so please be indulgence. In my app I am using jQuery, backbone.js and underscore.js and for tests mocha.js and chai.js. I have problem because I have no idea how to test events using this tools. Fox example I have function which changes value of input. It call after change checkbox value.
test.html file:
<!DOCTYPE html>
<html>
<head>
<title>Backbone.js Tests</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<link rel="stylesheet" href="js/lib/mocha.css" />
<script src="js/lib/mocha.js"></script>
<script src="js/lib/chai.js"></script>
<!-- <script src="js/lib/sinon.js"></script> -->
<script>
// Setup
var expect = chai.expect;
mocha.setup('bdd');
// Run tests on window load event.
window.onload = function () {
(window.mochaPhantomJS || mocha).run();
};
</script>
<!-- App code -->
<script src="../public/static/js/libs/jquery-2.1.4.min.js"></script>
<script src="../public/static/js/libs/js.cookie-2.1.0.min.js"></script>
<script src="../public/static/js/libs/bootstrap.min.js"></script>
<script src="../public/static/js/libs/underscore-min.js"></script>
<script src="../public/static/js/libs/backbone-min.js"></script>
<script src="../public/static/js/libs/backbone-relational.min.js"></script>
<script src="../public/static/js/libs/backbone-super.min.js"></script>
<script src="../public/static/js/libs/handlebars-v4.0.5.min.js"></script>
<script src="../public/static/js/application.js"></script>
<script src="../public/static/js/main.js"></script>
<script src="../public/static/js/views/register.js"></script>
<script src="../public/static/js/views/modals/sign-in-modal.js"></script>
<script src="../public/static/js/views/modals/sign-up-modal.js"></script>
<script src="../public/static/js/helpers/forms.js"></script>
<script src="../public/static/js/helpers/alerts.js"></script>
<script src="../public/static/js/helpers/inpage-alerts.js"></script>
<script src="../public/static/js/collections.js"></script>
<script src="../public/static/js/models.js"></script>
<script src="../public/static/js/kodilla.lib.js"></script>
<script src="../public/static/js/views/knowledge-base.js"></script>
<script src="../public/static/js/libs/tether.min.js"></script>
<!-- Tests -->
<script src="js/spec/register.spec.js"></script>
</head>
<body>
<div id="mocha"></div>
</body>
</html>
register.js file:
App.Views.Register = Backbone.View.extend({
events: {
'click input[name="terms"]' : 'changeTermsConfirmation',
'click [type=submit]': 'onSubmitForm'
},
initialize: function(options) {
this.$termsConfirmedAtHidden = this.$('input[name="terms_confirmed_at"]');
},
changeTermsConfirmation: function(e) {
if ($(e.currentTarget).is(":checked")) {
this.$termsConfirmedAtHidden.val(Math.floor(Date.now() / 1000));
} else {
this.$termsConfirmedAtHidden.val('');
}
},
onSubmitForm: function() {
if (!this.$el.find('input[name="terms"]').is(':checked')) {
analytics.track('auth_register_not_checked_terms');
}
}
});
register.spec.js file:
$(document).ready(function() {
describe('Register Form', function() {
App.registerView = new App.Views.Register();
describe('initialize() function', function() {
it('Should initialize this.$termsConfirmedAtHidden variable by HTML object', function () {
expect(App.registerView.$termsConfirmedAtHidden).to.be.a('object');
});
});
describe('changeTermsConfirmation() function', function() {
it('Should set value of $termsConfirmedAtHidden element', function () {
//how to test this function
});
});
});
});
My question is how to write sensible unit test for "changeTermsConfirmation()" function. I'll be thankful for others notes, usage tips.
Maybe I can help you out with a few bits of info which might get you started.
Mocha/Chai is modular, so first you need to include a mocking/spying library into your project. The default choice for most people seems to be Sinon (along with Sinon-Chai).
Then you can examine and unit test your event handler:
Create a view instance for your test.
Set up a spy on the view method you want to test (changeTermsConfirmation in your case)
Trigger the event by calling trigger on your view instance
Your expectation can check how often your method has been called, and with which arguments, and what its return value has been.
If you don't care about any of that and just want to test view state changes, you don't need a spy (and you don't need to include a library like Sinon). Just create a view instance, call trigger and examine the result.
Is it possible to executeScript() on loadstart event in Cordova inAppBrowser? Here is my standalone example I made to try to make it happen:
<!DOCTYPE html>
<html>
<head>
<title>Standalone Example</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
document.addEventListener("deviceready", onDeviceReady, false);
var iabRef = null;
function testFunction() {
iabRef.executeScript({
code: {'alert("It is alive! ALIVE!")'}
});
}
function onDeviceReady() {
iabRef = window.open('http://telegraph.co.uk', '_self', 'location=no', 'zoom=no', 'hardwareback=yes');
iabRef.addEventListener('loadstart', testFunction);
}
</script>
</head>
<body>
</body>
</html>
Doesn't work for me though. Config.xml allow origin is set to *. Any suggestions?
Thanks!
Yes, it possible to executeScript() on loadstart.Remove {} from alert part as follows:
function testFunction() {
iabRef.executeScript({
code: 'alert("It is alive! ALIVE!");'
});
}
Hope this works
After a little bit of wandering I found that changing "_self" to "_blank" makes it work. So:
iabRef = window.open('http://telegraph.co.uk', '_blank', 'location=no', 'zoom=no', 'hardwareback=yes');
I have a problem in a click button redirect to another page in cordova build, the error is an Uncaught ReferenceError: $ is not defined
// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkID=397704
// To debug code on page load in Ripple or on Android devices/emulators: launch your app, set breakpoints,
// and then run "window.location.reload()" in the JavaScript Console.
(function () {
"use strict";
document.addEventListener( 'deviceready', onDeviceReady.bind( this ), false );
function onDeviceReady() {
// Handle the Cordova pause and resume events
document.addEventListener( 'pause', onPause.bind( this ), false );
document.addEventListener('resume', onResume.bind(this), false);
$("getas").click(function () {
alert("The paragraph was clicked.");
});
// TODO: Cordova has been loaded. Perform any initialization that requires Cordova here.
};
function onPause() {
// TODO: This application has been suspended. Save application state here.
};
function onResume() {
// TODO: This application has been reactivated. Restore application state here.
};
} )();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<!--
Customize the content security policy in the meta tag below as needed. Add 'unsafe-inline' to default-src to enable inline JavaScript.
For details, see http://go.microsoft.com/fwlink/?LinkID=617521
-->
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *">
<title>CatechesisMobileApp</title>
<!-- MobileApp references -->
<link href="css/index.css" rel="stylesheet" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script src="cordova.js"></script>
<script src="scripts/platformOverrides.js"></script>
<script src="scripts/index.js"></script>
</head>
<body>
<p>Mobile App - Inicio</p>
<button id="getas">Ver Alunos (GET ALL)</button>
<br />
<br />
<button id="geta">Ver Aluno (GET ID)</button>
<br />
<br />
<button id="posta">Inserir Aluno (POST)</button>
<!-- Cordova reference, this is added to your app when it's built. -->
</body>
</html>
what am i doing wrong? I already try in onclick button "document.location.href='example.html'" and simply dont work
Thanks
Philip Clegg was very close in his comment. You need to pass jQuery into the closure. Here's an SO question explaining it
(function ($) {
"use strict";
document.addEventListener( 'deviceready', onDeviceReady.bind( this ), false );
function onDeviceReady() {
// Handle the Cordova pause and resume events
document.addEventListener( 'pause', onPause.bind( this ), false );
document.addEventListener('resume', onResume.bind(this), false);
$("#getas").click(function () {
alert("The paragraph was clicked.");
});
// TODO: Cordova has been loaded. Perform any initialization that requires Cordova here.
};
function onPause() {
// TODO: This application has been suspended. Save application state here.
};
function onResume() {
// TODO: This application has been reactivated. Restore application state here.
};
} )(jQuery);
getas is an id so you should select it with
$("#getas")
I'm starting to use Cordova 3.1.0 now. I use command line to generate a project and then modify the existing code.
I copy and paste the following code from official website to test.
<!DOCTYPE html>
<html>
<head>
<title>InAppBrowser.addEventListener Example</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
var ref = window.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstart', function(event) { alert('start: ' + event.url); });
ref.addEventListener('loadstop', function(event) { alert('stop: ' + event.url); });
ref.addEventListener('loaderror', function(event) { alert('error: ' + event.message); });
ref.addEventListener('exit', function(event) { alert(event.type); });
}
</script>
</head>
<body>
</body>
</html>
This doesn't work. There are no alert. Then I added a button to try to fire the events.
<!DOCTYPE html>
<html>
<head>
<title>InAppBrowser.addEventListener Example</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8" src="jquery.js"></script>
<script type="text/javascript" charset="utf-8">
// Wait for device API libraries to load
//
document.addEventListener("deviceready", onDeviceReady, false);
// device APIs are available
//
function onDeviceReady() {
$("#btn").click(function(){
var ref = window.open('http://apache.org', '_blank', 'location=yes');
ref.addEventListener('loadstart', function(event) { alert('start: ' + event.url); });
ref.addEventListener('loadstop', function(event) { alert('stop: ' + event.url); });
ref.addEventListener('loaderror', function(event) { alert('error: ' + event.message); });
ref.addEventListener('exit', function(event) { alert(event.type); });
});
}
</script>
</head>
<body>
<button id="btn">trigger</button>
</body>
</html>
This time, it works with second time. It means, it doesn't work when I click the button first time. But it works at the second time when I click the button. After that, I use console log inside the callback function to debug. The logs were not appeared at the first time (appeared at the second time and third, forth....).
I don't really know why this happened. I followed all steps from official website. Creating project, installing plugin, building and so on.
Could someone give me a hand?
I ran into the same problem. On further investigation, I found that the events weren't firing in the emulator / browser, but fired fine on the Nexus 7 device that I do my testing on. Hope that helps!
It looks like it's a problem with the last phonegap/cordova version 3.1.0.
https://groups.google.com/forum/#!topic/phonegap/e5_5unC2fYs
Try an older version.