I've wrote a simple app to test native dialogs. For simplicity, I will only include the code for firing the alert dialog. Here is the code:
index.html
<div id="alert" class="item">
<h1>Alert</h1>
<p>Title</p>
<input type="text" />
<p>Message</p>
<textarea></textarea>
<p>Button label</p>
<input type="text" />
<button onclick="alertDiag()" class="submit">GO</button>
</div>
main.js
window.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
function alertDiag() {
var message = document.getElementById("alert").children[4].value;
var title = document.getElementById("alert").children[2].value;
var buttonName = document.getElementById("alert").children[6].value;
function alertCallback() {
alert("The alert was dismissed");
}
navigator.notification.alert(message, alertCallback, title, buttonName);
}
}
config.xml
<?xml version='1.0' encoding='utf-8'?>
<widget id="com.phonegap.nativedialogues" version="1.0.0" xmlns="http://www.w3.org/ns/widgets" xmlns:gap="http://phonegap.com/ns/1.0">
<name>Testing Native Dialogues</name>
<description>
An application for testing native dialogues
</description>
<author email="example@gmail.com" href="http://www.example.com">
PhoneGap Team
</author>
<content src="index.html"/>
<preference name="DisallowOverscroll" value="false"/>
<access origin="*"/>
<plugin name="cordova-plugin-dialogs" spec="~1.3.4"/>
</widget>
However, since alertDiag()
is wrapped inside the deviceReady
event listener, it is undefined when invoked via the button click. In the console I get the following error:
Cannot get property 'alert' of undefined
What can I do to make the function only available after the device is ready, but at the same time be able to execute it when the button is clicked?
I am using the phonegap cloud build service for packaging the apps, not the local phonegap cli.
Firstly, as you may have understood, deviceready
is an event fired when Cordova has finished loading all plugins for your app. It's just an indication to let you know that if there be a logic that accesses any plugin on page load, then it should ideally go inside the device ready callback.
In your case, the alertDiag()
is called on user interaction and not on page load. This means you need to define it outside the deviceready
callback.
window.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
// any logic on page load
}
function alertDiag() {
var message = document.getElementById("alert").children[4].value;
var title = document.getElementById("alert").children[2].value;
var buttonName = document.getElementById("alert").children[6].value;
function alertCallback() {
alert("The alert was dismissed");
}
navigator.notification.alert(message, alertCallback, title, buttonName);
}