I'm trying to put an alert on a button in Cordova, I don't understand why it's not working.
I started a new cordova blank project with console.
See below my code :
index.html
<!DOCTYPE html>
<html>
<head>
<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 *">
<meta name="format-detection" content="telephone=no">
<meta name="msapplication-tap-highlight" content="no">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width">
<link rel="stylesheet" type="text/css" href="css/index.css">
<title>Hello World</title>
</head>
<body>
<button id = "textlocal">Test Local</button>`
<script type="text/javascript" src="cordova.js"></script>
<script type="text/javascript" src="js/index.js"></script>
</body>
</html>
index.js :
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
document.getElementById("textlocal").addEventListener("click", textLocal);
},
// Update DOM on a Received Event
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
},
function textLocal(){
alert('test');
}
};
app.initialize();
Maybe my textLocal() function is not at the right place, but I can't figurate how to fix it.
Thank you a lot for your patience and your help.
There was a JavaScript error in your code. Please try this code now. Maybe you need to add the "textLocal" listener up to the "deviceready" listener.
Code
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function() {
app.receivedEvent('deviceready');
document.getElementById("textlocal").addEventListener("click", this.textLocal);
},
// Update DOM on a Received Event
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id);
},
textLocal: function() {
alert('Test');
}
};
app.initialize();
Your code have a syntax error.
And this function never will call if you not associate with button.
You need put a onclick listener. You can use onclick tag like this:
<button id="textlocal" onclick="textLocal()">Test Local</button> (without space)
or using jquery
$("#textlocal").on("click", textLocal);
Remove this from head tag and try
<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 *">
If still its not working, your deviceready function executing before DOM load. So you should put it inside $(document).ready if you are using jquery or just in onload event. By the way add addEventListener is not good approach for such simple operation, just use onclick listener.
I allow myself to bring an interesting way to understand why it's not working. I'm not so familiar with cordova development but I create a cordova project on Visual Studio and get this :
index.html
<button id="textlocal" data-role="button">Alert</button>
index.js (in ondevice ready) :
$('#textlocal').click(textLocal);
test.js :
function textLocal() {
alert('test');}
And this solution works. However, I wouldn't like to work on visual studio but directly with command prompt and outside any editor.
It's a little the same thing as my demand above, but still can't find a way to make it happend. Hope that could help you to answer my problem.
Thank you.
Related
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>
THE APP
I'm trying to create a simple app which takes a picture, am testing phonegap build
When the app loads I get a console log saying deviceready - which is logged when the device is ready
THE PROBLEM
When I click the button to fire the camera, I get a console error:
Uncaught TypeError: Cannot read property 'getPicture' of undefined
JS / HTML
<button onclick="app.takePicture();">Take Picture</button>
<script type="text/javascript" src="phonegap.js"></script>
<script>
var app = {
// Application Constructor
initialize: function() {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
// 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() {
app.receivedEvent('deviceready');
},
// Update DOM on a Received Event
receivedEvent: function(id) {
var parentElement = document.getElementById(id);
var listeningElement = parentElement.querySelector('.listening');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
console.log('Received Event: ' + id); // <-- this works ok
},
takePicture: function() {
navigator.camera.getPicture( function( imageURI ) {
alert( imageURI );
},
function( message ) {
alert( message );
},
{
quality: 50,
destinationType: Camera.DestinationType.FILE_URI
});
}
};
app.initialize();
</script>
I also tried with cordova.js but same issue exactly.
I've seen this issue mentioned before but cannot find a fix for it, is there one? Is there a better way to do this?
Figured it out although can't find this documented anywhere!
Make sure you add this to your config.xml file:
<plugin name="org.apache.cordova.camera" spec="0.3.6" source="pgb" />
This basically, from what I can gather, creates the navigator object
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 cannot get any data if I use different domains. If I run it on the same server, no problem with it - message is obtained.
index.html:
<head>
<title>Test 1</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function popupResize() {
var popup = window.open('popup.html', '', 'resizable=yes,scrollbars=yes,width=500,height=500');
// var popup = window.open('https://foo/index.html', '', 'resizable=yes,scrollbars=yes,width=500,height=500');
window.addEventListener(
'message',
function(event) {
console.log(event.data);
},
false
);
}
</script>
</head>
<body>
Go!
</body>
popup.html:
<head>
<title>Game history details</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script>
function postSize() {
var h = 100;
var w = 200;
opener.postMessage([h, w], '*');
}
</script>
</head>
<body onload="postSize();">
test 1
</body>
How to get it working using different servers?
Problem 1
popup.addEventListener(
You need to listen for the event on your original window, not on the popup. The popup is where the message comes from, not where it is sent.
Use window.addEventListener( or just addEventListener(.
Problem 2
{h, w}
ES6 shorthand property names are not supported by IE, Opera, Safari or Android Mobile. They are best avoided.
Problem 3
parent.postMessage({h, w}, '*');
You are sending a message to the opening window, not the parent frame. There is no parent frame (so parent recurses onto window).
That should be:
opener.postMessage({h: h, w: w}, '*');
Problem 4
<script type="text/javascript">
var popup = window.open('popup.html', '', 'resizable=yes,scrollbars=yes,width=500,height=500');
Your script does not have permission to open a new window except in response to a user event. That code needs moving into a function and then called from, for instance, a click event.
If I run it on the same server, no problem with it - message is obtained.
It is the combination of problems 1 and 3 that cause this. You are binding an event handler to the popup (which you can only do from the opening window if it is on the same origin) and you are posting a message from the popup to itself (because parent === window).
Complete, albeit not best practise, code that works in my tests:
http://localhost:7007/index.html
<!DOCTYPE html>
<html>
<script>
addEventListener("message", function (event) {
document.body.appendChild(document.createTextNode(event.data));
});
function pop() {
window.open("http://127.0.0.1:7007/popup.html");
}
</script>
<input type="button" onclick="pop()">
http://127.0.0.1:7007/popup.html
<!DOCTYPE html>
<html>
<script>
opener.postMessage([123, 456], '*');
</script>
<h1>popup</h1>
The eventListener should be attached to window instead of popup:
window.addEventListener(
'message',
function (event) {
console.log(event.data);
},
false
);
In your child window (popup), you are posting a message to the parent window, but the eventListener is attached to the child window instead.
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.