This commit is contained in:
nicco
2018-09-04 19:47:42 +02:00
parent 8ba2030bb3
commit 94c02d6a2e
472 changed files with 63790 additions and 12 deletions

View File

@@ -0,0 +1,37 @@
<!--
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
#
-->
# Contributing to Apache Cordova
Anyone can contribute to Cordova. And we need your contributions.
There are multiple ways to contribute: report bugs, improve the docs, and
contribute code.
For instructions on this, start with the
[contribution overview](http://cordova.apache.org/contribute/).
The details are explained there, but the important items are:
- Sign and submit an Apache ICLA (Contributor License Agreement).
- Have a Jira issue open that corresponds to your contribution.
- Run the tests so your patch doesn't break existing functionality.
We look forward to your contributions!

View File

@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,5 @@
Apache Cordova
Copyright 2012 The Apache Software Foundation
This product includes software developed at
The Apache Software Foundation (http://www.apache.org/).

View File

@@ -0,0 +1,225 @@
---
title: Dialogs
description: Use native dialog UI elements
---
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
|AppVeyor|Travis CI|
|:-:|:-:|
|[![Build status](https://ci.appveyor.com/api/projects/status/github/apache/cordova-plugin-dialogs?branch=master)](https://ci.appveyor.com/project/ApacheSoftwareFoundation/cordova-plugin-dialogs)|[![Build Status](https://travis-ci.org/apache/cordova-plugin-dialogs.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-dialogs)|
# cordova-plugin-dialogs
This plugin provides access to some native dialog UI elements
via a global `navigator.notification` object.
Although the object is attached to the global scoped `navigator`, it is not available until after the `deviceready` event.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.notification);
}
Report issues on the [Apache Cordova issue tracker](https://issues.apache.org/jira/issues/?jql=project%20%3D%20CB%20AND%20status%20in%20%28Open%2C%20%22In%20Progress%22%2C%20Reopened%29%20AND%20resolution%20%3D%20Unresolved%20AND%20component%20%3D%20%22Plugin%20Dialogs%22%20ORDER%20BY%20priority%20DESC%2C%20summary%20ASC%2C%20updatedDate%20DESC)
## Installation
cordova plugin add cordova-plugin-dialogs
## Methods
- `navigator.notification.alert`
- `navigator.notification.confirm`
- `navigator.notification.prompt`
- `navigator.notification.beep`
## navigator.notification.alert
Shows a custom alert or dialog box. Most Cordova implementations use a native
dialog box for this feature, but some platforms use the browser's `alert`
function, which is typically less customizable.
navigator.notification.alert(message, alertCallback, [title], [buttonName])
- __message__: Dialog message. _(String)_
- __alertCallback__: Callback to invoke when alert dialog is dismissed. _(Function)_
- __title__: Dialog title. _(String)_ (Optional, defaults to `Alert`)
- __buttonName__: Button name. _(String)_ (Optional, defaults to `OK`)
### Example
function alertDismissed() {
// do something
}
navigator.notification.alert(
'You are the winner!', // message
alertDismissed, // callback
'Game Over', // title
'Done' // buttonName
);
### Supported Platforms
- Android
- Browser
- iOS
- Windows
## navigator.notification.confirm
Displays a customizable confirmation dialog box.
navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels])
- __message__: Dialog message. _(String)_
- __confirmCallback__: Callback to invoke with index of button pressed (1, 2, or 3) or when the dialog is dismissed without a button press (0). _(Function)_
- __title__: Dialog title. _(String)_ (Optional, defaults to `Confirm`)
- __buttonLabels__: Array of strings specifying button labels. _(Array)_ (Optional, defaults to [`OK,Cancel`])
### confirmCallback
The `confirmCallback` executes when the user presses one of the
buttons in the confirmation dialog box.
The callback takes the argument `buttonIndex` _(Number)_, which is the
index of the pressed button. Note that the index uses one-based
indexing, so the value is `1`, `2`, `3`, etc.
### Example
function onConfirm(buttonIndex) {
alert('You selected button ' + buttonIndex);
}
navigator.notification.confirm(
'You are the winner!', // message
onConfirm, // callback to invoke with index of button pressed
'Game Over', // title
['Restart','Exit'] // buttonLabels
);
### Supported Platforms
- Android
- Browser
- iOS
- Windows
### Android Quirks
- Android supports a maximum of three buttons, and ignores any more than that.
### Windows Quirks
- On Windows8/8.1 it is not possible to add more than three buttons to MessageDialog instance.
- On Windows Phone 8.1 it's not possible to show dialog with more than two buttons.
## navigator.notification.prompt
Displays a native dialog box that is more customizable than the browser's `prompt` function.
navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText])
- __message__: Dialog message. _(String)_
- __promptCallback__: Callback to invoke with index of button pressed (1, 2, or 3) or when the dialog is dismissed without a button press (0). _(Function)_
- __title__: Dialog title _(String)_ (Optional, defaults to `Prompt`)
- __buttonLabels__: Array of strings specifying button labels _(Array)_ (Optional, defaults to `["OK","Cancel"]`)
- __defaultText__: Default textbox input value (`String`) (Optional, Default: empty string)
### promptCallback
The `promptCallback` executes when the user presses one of the buttons
in the prompt dialog box. The `results` object passed to the callback
contains the following properties:
- __buttonIndex__: The index of the pressed button. _(Number)_ Note that the index uses one-based indexing, so the value is `1`, `2`, `3`, etc.
- __input1__: The text entered in the prompt dialog box. _(String)_
### Example
function onPrompt(results) {
alert("You selected button number " + results.buttonIndex + " and entered " + results.input1);
}
navigator.notification.prompt(
'Please enter your name', // message
onPrompt, // callback to invoke
'Registration', // title
['Ok','Exit'], // buttonLabels
'Jane Doe' // defaultText
);
### Supported Platforms
- Android
- Browser
- iOS
- Windows
### Android Quirks
- Android supports a maximum of three buttons, and ignores any more than that.
- On Android 3.0 and later, buttons are displayed in reverse order for devices that use the Holo theme.
### Windows Quirks
- On Windows prompt dialog is html-based due to lack of such native api.
## navigator.notification.beep
The device plays a beep sound.
navigator.notification.beep(times);
- __times__: The number of times to repeat the beep. _(Number)_
### Example
// Beep twice!
navigator.notification.beep(2);
### Supported Platforms
- Android
- Browser
- iOS
- Windows 8
### Android Quirks
- Android plays the default __Notification ringtone__ specified under the __Settings/Sound & Display__ panel.

View File

@@ -0,0 +1,3 @@
### 2.0.1 (Dec 27, 2017)
* [CB-13703](https://issues.apache.org/jira/browse/CB-13703) Fix to allow 2.0.0 version install

View File

@@ -0,0 +1,275 @@
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-dialogs
[![Build Status](https://travis-ci.org/apache/cordova-plugin-dialogs.svg)](https://travis-ci.org/apache/cordova-plugin-dialogs)
Dieses Plugin ermöglicht den Zugriff auf einige native Dialog-UI-Elemente über eine globale `navigator.notification`-Objekt.
Obwohl das Objekt mit der globalen Gültigkeitsbereich `navigator` verbunden ist, steht es nicht bis nach dem `Deviceready`-Ereignis.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.notification);
}
## Installation
cordova plugin add cordova-plugin-dialogs
## Methoden
* `navigator.notification.alert`
* `navigator.notification.confirm`
* `navigator.notification.prompt`
* `navigator.notification.beep`
## navigator.notification.alert
Zeigt eine benutzerdefinierte Warnung oder Dialogfeld Feld. Die meisten Implementierungen von Cordova ein native Dialogfeld für dieses Feature verwenden, jedoch einige Plattformen des Browsers-`alert`-Funktion, die in der Regel weniger anpassbar ist.
navigator.notification.alert(message, alertCallback, [title], [buttonName])
* **Nachricht**: Dialogfeld Nachricht. *(String)*
* **AlertCallback**: Callback aufgerufen wird, wenn Warnungs-Dialogfeld geschlossen wird. *(Funktion)*
* **Titel**: Dialog "Titel". *(String)* (Optional, Standard ist`Alert`)
* **ButtonName**: Name der Schaltfläche. *(String)* (Optional, Standard ist`OK`)
### Beispiel
function alertDismissed() {
// do something
}
navigator.notification.alert(
'You are the winner!', // message
alertDismissed, // callback
'Game Over', // title
'Done' // buttonName
);
### Unterstützte Plattformen
* Amazon Fire OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 und 8
* Windows 8
* Windows
### Windows Phone 7 und 8 Eigenarten
* Es gibt keine eingebaute Datenbanksuchroutine-Warnung, aber Sie können binden, wie folgt zu nennen `alert()` im globalen Gültigkeitsbereich:
window.alert = navigator.notification.alert;
* Beide `alert` und `confirm` sind nicht blockierende Aufrufe, die Ergebnisse davon nur asynchron sind.
### Firefox OS Macken:
Native blockierenden `window.alert()` und nicht-blockierende `navigator.notification.alert()` zur Verfügung.
### BlackBerry 10 Macken
`navigator.notification.alert ('Text', Rückruf, 'Titel', 'Text')` Callback-Parameter wird die Zahl 1 übergeben.
## navigator.notification.confirm
Zeigt das Dialogfeld anpassbare Bestätigung.
navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels])
* **Nachricht**: Dialogfeld Nachricht. *(String)*
* **ConfirmCallback**: Callback aufgerufen wird, mit Index gedrückt (1, 2 oder 3) oder wenn das Dialogfeld geschlossen wird, ohne einen Tastendruck (0). *(Funktion)*
* **Titel**: Dialog "Titel". *(String)* (Optional, Standard ist`Confirm`)
* **ButtonLabels**: Array von Zeichenfolgen, die Schaltflächenbezeichnungen angeben. *(Array)* (Optional, Standard ist [ `OK,Cancel` ])
### confirmCallback
Die `confirmCallback` wird ausgeführt, wenn der Benutzer eine der Schaltflächen im Dialogfeld zur Bestätigung drückt.
Der Rückruf dauert das Argument `buttonIndex` *(Anzahl)*, die der Index der Schaltfläche gedrückt ist. Beachten Sie, dass der Index 1-basierte Indizierung, sodass der Wert `1`, `2`, `3` usw. ist.
### Beispiel
function onConfirm(buttonIndex) {
alert('You selected button ' + buttonIndex);
}
navigator.notification.confirm(
'You are the winner!', // message
onConfirm, // callback to invoke with index of button pressed
'Game Over', // title
['Restart','Exit'] // buttonLabels
);
### Unterstützte Plattformen
* Amazon Fire OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 und 8
* Windows 8
* Windows
### Windows Phone 7 und 8 Eigenarten
* Es gibt keine integrierte Browser-Funktion für `window.confirm` , aber Sie können es binden, indem Sie zuweisen:
window.confirm = navigator.notification.confirm;
* Aufrufe von `alert` und `confirm` sind nicht blockierend, so dass das Ergebnis nur asynchron zur Verfügung steht.
### Windows-Eigenheiten
* Auf Windows8/8.1 kann nicht mehr als drei Schaltflächen MessageDialog-Instanz hinzu.
* Auf Windows Phone 8.1 ist es nicht möglich, Dialog mit mehr als zwei Knöpfen zeigen.
### Firefox OS Macken:
Native blockierenden `window.confirm()` und nicht-blockierende `navigator.notification.confirm()` zur Verfügung.
## navigator.notification.prompt
Zeigt eine native Dialogfeld, das mehr als `Prompt`-Funktion des Browsers anpassbar ist.
navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText])
* **Nachricht**: Dialogfeld Nachricht. *(String)*
* **promptCallback**: Callback aufgerufen wird, mit Index gedrückt (1, 2 oder 3) oder wenn das Dialogfeld geschlossen wird, ohne einen Tastendruck (0). *(Funktion)*
* **title**: Dialog Title *(String)* (Optional, Standard ist `Prompt`)
* **buttonLabels**: Array von Zeichenfolgen angeben Schaltfläche Etiketten *(Array)* (Optional, Standard ist `["OK", "Abbrechen"]`)
* **defaultText**: Standard-Textbox Eingabewert (`String`) (Optional, Standard: leere Zeichenfolge)
### promptCallback
Die `promptCallback` wird ausgeführt, wenn der Benutzer eine der Schaltflächen im Eingabedialogfeld drückt. `Des Objekts an den Rückruf übergeben` enthält die folgenden Eigenschaften:
* **buttonIndex**: der Index der Schaltfläche gedrückt. *(Anzahl)* Beachten Sie, dass der Index 1-basierte Indizierung, sodass der Wert `1`, `2`, `3` usw. ist.
* **input1**: in Eingabedialogfeld eingegebenen Text. *(String)*
### Beispiel
function onPrompt(results) {
alert("You selected button number " + results.buttonIndex + " and entered " + results.input1);
}
navigator.notification.prompt(
'Please enter your name', // message
onPrompt, // callback to invoke
'Registration', // title
['Ok','Exit'], // buttonLabels
'Jane Doe' // defaultText
);
### Unterstützte Plattformen
* Amazon Fire OS
* Android
* Firefox OS
* iOS
* Windows Phone 7 und 8
* Windows 8
* Windows
### Android Eigenarten
* Android unterstützt maximal drei Schaltflächen und mehr als das ignoriert.
* Auf Android 3.0 und höher, werden die Schaltflächen in umgekehrter Reihenfolge für Geräte angezeigt, die das Holo-Design verwenden.
### Windows-Eigenheiten
* Unter Windows ist Prompt Dialogfeld html-basierten mangels solcher native api.
### Firefox OS Macken:
Native blockierenden `window.prompt()` und nicht-blockierende `navigator.notification.prompt()` zur Verfügung.
## navigator.notification.beep
Das Gerät spielt einen Signalton sound.
navigator.notification.beep(times);
* **times**: die Anzahl der Wiederholungen des Signaltons. *(Anzahl)*
### Beispiel
// Beep twice!
navigator.notification.beep(2);
### Unterstützte Plattformen
* Amazon Fire OS
* Android
* BlackBerry 10
* iOS
* Tizen
* Windows Phone 7 und 8
* Windows 8
### Amazon Fire OS Macken
* Amazon Fire OS spielt die Standardeinstellung **Akustische Benachrichtigung** unter **Einstellungen/Display & Sound** Bereich angegeben.
### Android Eigenarten
* Android spielt die Standardeinstellung **Benachrichtigung Klingelton** unter **Einstellungen/Sound & Display**-Panel angegeben.
### Windows Phone 7 und 8 Eigenarten
* Stützt sich auf eine generische Piepton-Datei aus der Cordova-Distribution.
### Tizen Macken
* Tizen implementiert Signaltöne durch Abspielen einer Audiodatei über die Medien API.
* Die Beep-Datei muss kurz sein, in einem `sounds`-Unterverzeichnis des Stammverzeichnisses der Anwendung befinden muss und muss den Namen `beep.wav`.

View File

@@ -0,0 +1,273 @@
<!---
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# cordova-plugin-dialogs
Dieses Plugin ermöglicht den Zugriff auf einige native Dialog-UI-Elemente über eine globale `navigator.notification`-Objekt.
Obwohl das Objekt mit der globalen Gültigkeitsbereich `navigator` verbunden ist, steht es nicht bis nach dem `Deviceready`-Ereignis.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.notification);
}
## Installation
cordova plugin add cordova-plugin-dialogs
## Methoden
* `navigator.notification.alert`
* `navigator.notification.confirm`
* `navigator.notification.prompt`
* `navigator.notification.beep`
## navigator.notification.alert
Zeigt eine benutzerdefinierte Warnung oder Dialogfeld Feld. Die meisten Implementierungen von Cordova ein native Dialogfeld für dieses Feature verwenden, jedoch einige Plattformen des Browsers-`alert`-Funktion, die in der Regel weniger anpassbar ist.
navigator.notification.alert(message, alertCallback, [title], [buttonName])
* **Nachricht**: Dialogfeld Nachricht. *(String)*
* **AlertCallback**: Callback aufgerufen wird, wenn Warnungs-Dialogfeld geschlossen wird. *(Funktion)*
* **Titel**: Dialog "Titel". *(String)* (Optional, Standard ist`Alert`)
* **ButtonName**: Name der Schaltfläche. *(String)* (Optional, Standard ist`OK`)
### Beispiel
function alertDismissed() {
// do something
}
navigator.notification.alert(
'You are the winner!', // message
alertDismissed, // callback
'Game Over', // title
'Done' // buttonName
);
### Unterstützte Plattformen
* Amazon Fire OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 und 8
* Windows 8
* Windows
### Windows Phone 7 und 8 Eigenarten
* Es gibt keine eingebaute Datenbanksuchroutine-Warnung, aber Sie können binden, wie folgt zu nennen `alert()` im globalen Gültigkeitsbereich:
window.alert = navigator.notification.alert;
* Beide `alert` und `confirm` sind nicht blockierende Aufrufe, die Ergebnisse davon nur asynchron sind.
### Firefox OS Macken:
Native blockierenden `window.alert()` und nicht-blockierende `navigator.notification.alert()` zur Verfügung.
### BlackBerry 10 Macken
`navigator.notification.alert ('Text', Rückruf, 'Titel', 'Text')` Callback-Parameter wird die Zahl 1 übergeben.
## navigator.notification.confirm
Zeigt das Dialogfeld anpassbare Bestätigung.
navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels])
* **Nachricht**: Dialogfeld Nachricht. *(String)*
* **ConfirmCallback**: Callback aufgerufen wird, mit Index gedrückt (1, 2 oder 3) oder wenn das Dialogfeld geschlossen wird, ohne einen Tastendruck (0). *(Funktion)*
* **Titel**: Dialog "Titel". *(String)* (Optional, Standard ist`Confirm`)
* **ButtonLabels**: Array von Zeichenfolgen, die Schaltflächenbezeichnungen angeben. *(Array)* (Optional, Standard ist [ `OK,Cancel` ])
### confirmCallback
Die `confirmCallback` wird ausgeführt, wenn der Benutzer eine der Schaltflächen im Dialogfeld zur Bestätigung drückt.
Der Rückruf dauert das Argument `buttonIndex` *(Anzahl)*, die der Index der Schaltfläche gedrückt ist. Beachten Sie, dass der Index 1-basierte Indizierung, sodass der Wert `1`, `2`, `3` usw. ist.
### Beispiel
function onConfirm(buttonIndex) {
alert('You selected button ' + buttonIndex);
}
navigator.notification.confirm(
'You are the winner!', // message
onConfirm, // callback to invoke with index of button pressed
'Game Over', // title
['Restart','Exit'] // buttonLabels
);
### Unterstützte Plattformen
* Amazon Fire OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 und 8
* Windows 8
* Windows
### Windows Phone 7 und 8 Eigenarten
* Es gibt keine integrierte Browser-Funktion für `window.confirm` , aber Sie können es binden, indem Sie zuweisen:
window.confirm = navigator.notification.confirm;
* Aufrufe von `alert` und `confirm` sind nicht blockierend, so dass das Ergebnis nur asynchron zur Verfügung steht.
### Windows-Eigenheiten
* Auf Windows8/8.1 kann nicht mehr als drei Schaltflächen MessageDialog-Instanz hinzu.
* Auf Windows Phone 8.1 ist es nicht möglich, Dialog mit mehr als zwei Knöpfen zeigen.
### Firefox OS Macken:
Native blockierenden `window.confirm()` und nicht-blockierende `navigator.notification.confirm()` zur Verfügung.
## navigator.notification.prompt
Zeigt eine native Dialogfeld, das mehr als `Prompt`-Funktion des Browsers anpassbar ist.
navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText])
* **Nachricht**: Dialogfeld Nachricht. *(String)*
* **promptCallback**: Callback aufgerufen wird, mit Index gedrückt (1, 2 oder 3) oder wenn das Dialogfeld geschlossen wird, ohne einen Tastendruck (0). *(Funktion)*
* **title**: Dialog Title *(String)* (Optional, Standard ist `Prompt`)
* **buttonLabels**: Array von Zeichenfolgen angeben Schaltfläche Etiketten *(Array)* (Optional, Standard ist `["OK", "Abbrechen"]`)
* **defaultText**: Standard-Textbox Eingabewert (`String`) (Optional, Standard: leere Zeichenfolge)
### promptCallback
Die `promptCallback` wird ausgeführt, wenn der Benutzer eine der Schaltflächen im Eingabedialogfeld drückt. `Des Objekts an den Rückruf übergeben` enthält die folgenden Eigenschaften:
* **buttonIndex**: der Index der Schaltfläche gedrückt. *(Anzahl)* Beachten Sie, dass der Index 1-basierte Indizierung, sodass der Wert `1`, `2`, `3` usw. ist.
* **input1**: in Eingabedialogfeld eingegebenen Text. *(String)*
### Beispiel
function onPrompt(results) {
alert("You selected button number " + results.buttonIndex + " and entered " + results.input1);
}
navigator.notification.prompt(
'Please enter your name', // message
onPrompt, // callback to invoke
'Registration', // title
['Ok','Exit'], // buttonLabels
'Jane Doe' // defaultText
);
### Unterstützte Plattformen
* Amazon Fire OS
* Android
* Firefox OS
* iOS
* Windows Phone 7 und 8
* Windows 8
* Windows
### Android Eigenarten
* Android unterstützt maximal drei Schaltflächen und mehr als das ignoriert.
* Auf Android 3.0 und höher, werden die Schaltflächen in umgekehrter Reihenfolge für Geräte angezeigt, die das Holo-Design verwenden.
### Windows-Eigenheiten
* Unter Windows ist Prompt Dialogfeld html-basierten mangels solcher native api.
### Firefox OS Macken:
Native blockierenden `window.prompt()` und nicht-blockierende `navigator.notification.prompt()` zur Verfügung.
## navigator.notification.beep
Das Gerät spielt einen Signalton sound.
navigator.notification.beep(times);
* **times**: die Anzahl der Wiederholungen des Signaltons. *(Anzahl)*
### Beispiel
// Beep twice!
navigator.notification.beep(2);
### Unterstützte Plattformen
* Amazon Fire OS
* Android
* BlackBerry 10
* iOS
* Tizen
* Windows Phone 7 und 8
* Windows 8
### Amazon Fire OS Macken
* Amazon Fire OS spielt die Standardeinstellung **Akustische Benachrichtigung** unter **Einstellungen/Display & Sound** Bereich angegeben.
### Android Eigenarten
* Android spielt die Standardeinstellung **Benachrichtigung Klingelton** unter **Einstellungen/Sound & Display**-Panel angegeben.
### Windows Phone 7 und 8 Eigenarten
* Stützt sich auf eine generische Piepton-Datei aus der Cordova-Distribution.
### Tizen Macken
* Tizen implementiert Signaltöne durch Abspielen einer Audiodatei über die Medien API.
* Die Beep-Datei muss kurz sein, in einem `sounds`-Unterverzeichnis des Stammverzeichnisses der Anwendung befinden muss und muss den Namen `beep.wav`.

View File

@@ -0,0 +1,275 @@
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-dialogs
[![Build Status](https://travis-ci.org/apache/cordova-plugin-dialogs.svg)](https://travis-ci.org/apache/cordova-plugin-dialogs)
Este plugin permite acceder a algunos elementos de interfaz de usuario nativa diálogo vía global `navigator.notification` objeto.
Aunque el objeto está unido al ámbito global `navigator` , no estará disponible hasta después de la `deviceready` evento.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.notification);
}
## Instalación
cordova plugin add cordova-plugin-dialogs
## Métodos
* `navigator.notification.alert`
* `navigator.notification.confirm`
* `navigator.notification.prompt`
* `navigator.notification.beep`
## navigator.notification.alert
Muestra un cuadro de alerta o cuadro de diálogo personalizado. La mayoría de las implementaciones de Cordova utilizan un cuadro de diálogo nativa para esta característica, pero algunas plataformas utilizan el navegador `alert` la función, que es típicamente menos personalizable.
navigator.notification.alert(message, alertCallback, [title], [buttonName])
* **message**: mensaje de diálogo. *(String)*
* **alertCallback**: Callback para invocar al diálogo de alerta es desestimada. *(Función)*
* **title**: título de diálogo. *(String)* (Opcional, el valor predeterminado de `Alert`)
* **buttonName**: nombre del botón. *(String)* (Opcional, por defecto `Aceptar`)
### Ejemplo
function alertDismissed() {
// do something
}
navigator.notification.alert(
'You are the winner!', // message
alertDismissed, // callback
'Game Over', // title
'Done' // buttonName
);
### Plataformas soportadas
* Amazon fire OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 y 8
* Windows 8
* Windows
### Windows Phone 7 y 8 rarezas
* No hay ninguna alerta del navegador integrado, pero puede enlazar uno proceda a llamar `alert()` en el ámbito global:
window.alert = navigator.notification.alert;
* `alert` y `confirm` son non-blocking llamadas, cuyos resultados sólo están disponibles de forma asincrónica.
### Firefox OS rarezas:
Dos nativos de bloqueo `window.alert()` y no-bloqueo `navigator.notification.alert()` están disponibles.
### BlackBerry 10 rarezas
`navigator.notification.alert('text', callback, 'title', 'text')`parámetro de devolución de llamada se pasa el número 1.
## navigator.notification.confirm
Muestra un cuadro de diálogo de confirmación personalizables.
navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels])
* **message**: mensaje de diálogo. *(String)*
* **confirmCallback**: Callback para invocar con índice de botón pulsado (1, 2 o 3) o cuando el diálogo es despedido sin la presión del botón (0). *(Función)*
* **title**: título de diálogo. *(String)* (Opcional, por defecto a `confirmar`)
* **buttonLabels**: matriz de cadenas especificando las etiquetas de botón. *(Matriz)* (Opcional, por defecto [`OK, cancelar`])
### confirmCallback
El `confirmCallback` se ejecuta cuando el usuario presiona uno de los botones en el cuadro de diálogo de confirmación.
La devolución de llamada toma el argumento `buttonIndex` *(número)*, que es el índice del botón presionado. Observe que el índice utiliza indexación basada en uno, entonces el valor es `1` , `2` , `3` , etc..
### Ejemplo
function onConfirm(buttonIndex) {
alert('You selected button ' + buttonIndex);
}
navigator.notification.confirm(
'You are the winner!', // message
onConfirm, // callback to invoke with index of button pressed
'Game Over', // title
['Restart','Exit'] // buttonLabels
);
### Plataformas soportadas
* Amazon fire OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 y 8
* Windows 8
* Windows
### Windows Phone 7 y 8 rarezas
* No hay ninguna función de navegador incorporado para `window.confirm`, pero lo puede enlazar mediante la asignación:
window.confirm = navigator.notification.confirm;
* Llamadas de `alert` y `confirm` son non-blocking, así que el resultado sólo está disponible de forma asincrónica.
### Windows rarezas
* Sobre Windows8/8.1 no es posible agregar más de tres botones a instancia de MessageDialog.
* En Windows Phone 8.1 no es posible Mostrar cuadro de diálogo con más de dos botones.
### Firefox OS rarezas:
Dos nativos de bloqueo `window.confirm()` y no-bloqueo `navigator.notification.confirm()` están disponibles.
## navigator.notification.prompt
Muestra un cuadro de diálogo nativa que es más personalizable que del navegador `prompt` función.
navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText])
* **message**: mensaje de diálogo. *(String)*
* **promptCallback**: Callback para invocar con índice del botón pulsado (1, 2 ó 3) o cuando el cuadro de diálogo es despedido sin la presión del botón (0). *(Función)*
* **título**: título *(String)* (opcional, por defecto de diálogo`Prompt`)
* **buttonLabels**: matriz de cadenas especificando botón etiquetas *(Array)* (opcional, por defecto`["OK","Cancel"]`)
* **defaultText**: valor de la entrada predeterminada textbox ( `String` ) (opcional, por defecto: cadena vacía)
### promptCallback
El `promptCallback` se ejecuta cuando el usuario presiona uno de los botones del cuadro de diálogo pronto. El `results` objeto que se pasa a la devolución de llamada contiene las siguientes propiedades:
* **buttonIndex**: el índice del botón presionado. *(Número)* Observe que el índice utiliza indexación basada en uno, entonces el valor es `1` , `2` , `3` , etc..
* **INPUT1**: el texto introducido en el cuadro de diálogo pronto. *(String)*
### Ejemplo
function onPrompt(results) {
alert("You selected button number " + results.buttonIndex + " and entered " + results.input1);
}
navigator.notification.prompt(
'Please enter your name', // message
onPrompt, // callback to invoke
'Registration', // title
['Ok','Exit'], // buttonLabels
'Jane Doe' // defaultText
);
### Plataformas soportadas
* Amazon fire OS
* Android
* Firefox OS
* iOS
* Windows Phone 7 y 8
* Windows 8
* Windows
### Rarezas Android
* Android soporta un máximo de tres botones e ignora nada más.
* En Android 3.0 y posteriores, los botones aparecen en orden inverso para dispositivos que utilizan el tema Holo.
### Windows rarezas
* En Windows pronto diálogo está basado en html debido a falta de tal api nativa.
### Firefox OS rarezas:
Dos nativos de bloqueo `window.prompt()` y no-bloqueo `navigator.notification.prompt()` están disponibles.
## navigator.notification.beep
El aparato reproduce un sonido sonido.
navigator.notification.beep(times);
* **tiempos**: el número de veces a repetir la señal. *(Número)*
### Ejemplo
// Beep twice!
navigator.notification.beep(2);
### Plataformas soportadas
* Amazon fire OS
* Android
* BlackBerry 10
* iOS
* Tizen
* Windows Phone 7 y 8
* Windows 8
### Amazon fuego OS rarezas
* Amazon fuego OS reproduce el **Sonido de notificación** especificados en el panel de **configuración/pantalla y sonido** por defecto.
### Rarezas Android
* Androide reproduce el **tono de notificación** especificados en el panel **ajustes de sonido y visualización** por defecto.
### Windows Phone 7 y 8 rarezas
* Se basa en un archivo de sonido genérico de la distribución de Córdoba.
### Rarezas Tizen
* Tizen implementa pitidos por reproducir un archivo de audio a través de los medios de comunicación API.
* El archivo de sonido debe ser corto, debe estar ubicado en un `sounds` subdirectorio del directorio raíz de la aplicación y deben ser nombrados`beep.wav`.

View File

@@ -0,0 +1,247 @@
<!---
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# cordova-plugin-dialogs
Este plugin permite acceder a algunos elementos de interfaz de usuario nativa diálogo vía global `navigator.notification` objeto.
Aunque el objeto está unido al ámbito global `navigator` , no estará disponible hasta después de la `deviceready` evento.
document.addEventListener ("deviceready", onDeviceReady, false);
function onDeviceReady() {console.log(navigator.notification)};
## Instalación
Cordova plugin agregar cordova-plugin-dialogs
## Métodos
* `navigator.notification.alert`
* `navigator.notification.confirm`
* `navigator.notification.prompt`
* `navigator.notification.beep`
## navigator.notification.alert
Muestra un cuadro de alerta o cuadro de diálogo personalizado. La mayoría de las implementaciones de Cordova utilizan un cuadro de diálogo nativa para esta característica, pero algunas plataformas utilizan el navegador `alert` la función, que es típicamente menos personalizable.
Navigator.Notification.alert (mensaje, alertCallback, [title], [buttonName])
* **message**: mensaje de diálogo. *(String)*
* **alertCallback**: Callback para invocar al diálogo de alerta es desestimada. *(Función)*
* **title**: título de diálogo. *(String)* (Opcional, el valor predeterminado de `Alert`)
* **buttonName**: nombre del botón. *(String)* (Opcional, por defecto `Aceptar`)
### Ejemplo
function alertDismissed() {/ / hacer algo} navigator.notification.alert ('Tú eres el ganador!', / / mensaje alertDismissed, / / callback 'Game Over', / / título 'hecho' / / buttonName);
### Plataformas soportadas
* Amazon fire OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 y 8
* Windows 8
* Windows
### Windows Phone 7 y 8 rarezas
* No hay ninguna alerta del navegador integrado, pero puede enlazar uno proceda a llamar `alert()` en el ámbito global:
window.alert = navigator.notification.alert;
* `alert` y `confirm` son non-blocking llamadas, cuyos resultados sólo están disponibles de forma asincrónica.
### Firefox OS rarezas:
Dos nativos de bloqueo `window.alert()` y no-bloqueo `navigator.notification.alert()` están disponibles.
### BlackBerry 10 rarezas
`navigator.notification.alert('text', callback, 'title', 'text')`parámetro de devolución de llamada se pasa el número 1.
## navigator.notification.confirm
Muestra un cuadro de diálogo de confirmación personalizables.
Navigator.Notification.CONFIRM (mensaje, confirmCallback, [title], [buttonLabels])
* **message**: mensaje de diálogo. *(String)*
* **confirmCallback**: Callback para invocar con índice de botón pulsado (1, 2 o 3) o cuando el diálogo es despedido sin la presión del botón (0). *(Función)*
* **title**: título de diálogo. *(String)* (Opcional, por defecto a `confirmar`)
* **buttonLabels**: matriz de cadenas especificando las etiquetas de botón. *(Matriz)* (Opcional, por defecto [`OK, cancelar`])
### confirmCallback
El `confirmCallback` se ejecuta cuando el usuario presiona uno de los botones en el cuadro de diálogo de confirmación.
La devolución de llamada toma el argumento `buttonIndex` *(número)*, que es el índice del botón presionado. Observe que el índice utiliza indexación basada en uno, entonces el valor es `1` , `2` , `3` , etc..
### Ejemplo
function onConfirm(buttonIndex) {alert ('Tu botón seleccionado' + buttonIndex);}
Navigator.Notification.CONFIRM ('Tú eres el ganador!', / / mensaje onConfirm, / callback para invocar con índice del botón pulsado 'Game Over', / / / título ['reiniciar', 'Exit'] / / buttonLabels);
### Plataformas soportadas
* Amazon fire OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 y 8
* Windows 8
* Windows
### Windows Phone 7 y 8 rarezas
* No hay ninguna función de navegador incorporado para `window.confirm`, pero lo puede enlazar mediante la asignación:
window.confirm = navigator.notification.confirm;
* Llamadas de `alert` y `confirm` son non-blocking, así que el resultado sólo está disponible de forma asincrónica.
### Windows rarezas
* Sobre Windows8/8.1 no es posible agregar más de tres botones a instancia de MessageDialog.
* En Windows Phone 8.1 no es posible Mostrar cuadro de diálogo con más de dos botones.
### Firefox OS rarezas:
Dos nativos de bloqueo `window.confirm()` y no-bloqueo `navigator.notification.confirm()` están disponibles.
## navigator.notification.prompt
Muestra un cuadro de diálogo nativa que es más personalizable que del navegador `prompt` función.
Navigator.Notification.prompt (mensaje, promptCallback, [title], [buttonLabels], [defaultText])
* **mensaje**: mensaje de diálogo. *(String)*
* **promptCallback**: Callback para invocar con índice del botón pulsado (1, 2 ó 3) o cuando el cuadro de diálogo es despedido sin la presión del botón (0). *(Función)*
* **título**: título *(String)* (opcional, por defecto de diálogo`Prompt`)
* **buttonLabels**: matriz de cadenas especificando botón etiquetas *(Array)* (opcional, por defecto`["OK","Cancel"]`)
* **defaultText**: valor de la entrada predeterminada textbox ( `String` ) (opcional, por defecto: cadena vacía)
### promptCallback
El `promptCallback` se ejecuta cuando el usuario presiona uno de los botones del cuadro de diálogo pronto. El `results` objeto que se pasa a la devolución de llamada contiene las siguientes propiedades:
* **buttonIndex**: el índice del botón presionado. *(Número)* Observe que el índice utiliza indexación basada en uno, entonces el valor es `1` , `2` , `3` , etc..
* **INPUT1**: el texto introducido en el cuadro de diálogo pronto. *(String)*
### Ejemplo
function onPrompt(results) {alert ("seleccionaron botón número" + results.buttonIndex + "y entró en" + results.input1);}
Navigator.Notification.prompt ('Por favor introduce tu nombre', / / mensaje onPrompt, / / callback para invocar 'Registro', / / título ['Ok', 'Exit'], / / buttonLabels 'Jane Doe' / / defaultText);
### Plataformas soportadas
* Amazon fuego OS
* Android
* Firefox OS
* iOS
* Windows Phone 7 y 8
* Windows 8
* Windows
### Rarezas Android
* Android soporta un máximo de tres botones e ignora nada más.
* En Android 3.0 y posteriores, los botones aparecen en orden inverso para dispositivos que utilizan el tema Holo.
### Windows rarezas
* En Windows pronto diálogo está basado en html debido a falta de tal api nativa.
### Firefox OS rarezas:
Dos nativos de bloqueo `window.prompt()` y no-bloqueo `navigator.notification.prompt()` están disponibles.
## navigator.notification.beep
El aparato reproduce un sonido sonido.
Navigator.Notification.Beep(Times);
* **tiempos**: el número de veces a repetir la señal. *(Número)*
### Ejemplo
Dos pitidos.
Navigator.Notification.Beep(2);
### Plataformas soportadas
* Amazon fuego OS
* Android
* BlackBerry 10
* iOS
* Tizen
* Windows Phone 7 y 8
* Windows 8
### Amazon fuego OS rarezas
* Amazon fuego OS reproduce el **Sonido de notificación** especificados en el panel de **configuración/pantalla y sonido** por defecto.
### Rarezas Android
* Androide reproduce el **tono de notificación** especificados en el panel **ajustes de sonido y visualización** por defecto.
### Windows Phone 7 y 8 rarezas
* Se basa en un archivo de sonido genérico de la distribución de Córdoba.
### Rarezas Tizen
* Tizen implementa pitidos por reproducir un archivo de audio a través de los medios de comunicación API.
* El archivo de sonido debe ser corto, debe estar ubicado en un `sounds` subdirectorio del directorio raíz de la aplicación y deben ser nombrados`beep.wav`.

View File

@@ -0,0 +1,249 @@
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-dialogs
[![Build Status](https://travis-ci.org/apache/cordova-plugin-dialogs.svg)](https://travis-ci.org/apache/cordova-plugin-dialogs)
Ce plugin permet d'accéder à certains éléments d'interface utilisateur native de dialogue via un global `navigator.notification` objet.
Bien que l'objet est attaché à la portée globale `navigator` , il n'est pas disponible jusqu'après la `deviceready` événement.
document.addEventListener (« deviceready », onDeviceReady, false) ;
function onDeviceReady() {console.log(navigator.notification);}
## Installation
cordova plugin add cordova-plugin-dialogs
## Méthodes
* `navigator.notification.alert`
* `navigator.notification.confirm`
* `navigator.notification.prompt`
* `navigator.notification.beep`
## navigator.notification.alert
Affiche une boîte de dialogue ou d'alerte personnalisé. La plupart des implémentations de Cordova utilisent une boîte de dialogue natives pour cette fonctionnalité, mais certaines plates-formes du navigateur `alert` fonction, qui est généralement moins personnalisable.
Navigator.notification.Alert (message, alertCallback, [title], [buttonName])
* **message**: message de la boîte de dialogue. *(String)*
* **alertCallback**: callback à appeler lorsque la boîte de dialogue d'alerte est rejetée. *(Fonction)*
* **titre**: titre de la boîte de dialogue. *(String)* (Facultatif, par défaut`Alert`)
* **buttonName**: nom du bouton. *(String)* (Facultatif, par défaut`OK`)
### Exemple
function alertDismissed() {/ / faire quelque chose} navigator.notification.alert ('Vous êtes le gagnant!', / / message alertDismissed, / / rappel « Game Over », / / titre « Done » / / buttonName) ;
### Plates-formes supportées
* Amazon Fire OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Paciarelli
* Windows Phone 7 et 8
* Windows 8
* Windows
### Notes au sujet de Windows Phone 7 et 8
* Il n'y a aucune boîte de dialogue d'alerte intégrée au navigateur, mais vous pouvez en lier une pour appeler `alert()` dans le scope global:
window.alert = navigator.notification.alert;
* Les deux appels `alert` et `confirm` sont non-blocants, leurs résultats ne sont disponibles que de façon asynchrone.
### Firefox OS Quirks :
Les deux indigènes bloquant `window.alert()` et non-bloquante `navigator.notification.alert()` sont disponibles.
### BlackBerry 10 Quirks
`navigator.notification.alert('text', callback, 'title', 'text')`paramètre callback est passé numéro 1.
## navigator.notification.confirm
Affiche une boîte de dialogue de confirmation personnalisable.
Navigator.notification.Confirm (message, confirmCallback, [title], [buttonLabels])
* **message**: message de la boîte de dialogue. *(String)*
* **confirmCallback**: callback à appeler avec l'index du bouton pressé (1, 2 ou 3) ou lorsque la boîte de dialogue est fermée sans qu'un bouton ne soit pressé (0). *(Fonction)*
* **titre**: titre de dialogue. *(String)* (Facultatif, par défaut`Confirm`)
* **buttonLabels**: tableau de chaînes spécifiant les étiquettes des boutons. *(Array)* (Optionnel, par défaut, [ `OK,Cancel` ])
### confirmCallback
Le `confirmCallback` s'exécute lorsque l'utilisateur appuie sur un bouton dans la boîte de dialogue de confirmation.
Le rappel prend l'argument `buttonIndex` *(nombre)*, qui est l'index du bouton activé. Notez que l'index utilise base d'indexation, la valeur est `1` , `2` , `3` , etc..
### Exemple
function onConfirm(buttonIndex) {alert (« Vous bouton sélectionné » + buttonIndex);}
Navigator.notification.Confirm ('Vous êtes le gagnant!', / / message onConfirm, / / rappel d'invoquer avec l'index du bouton enfoncé « Game Over », / / title ['redémarrer', « Exit »] / / buttonLabels) ;
### Plates-formes supportées
* Amazon Fire OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Paciarelli
* Windows Phone 7 et 8
* Windows 8
* Windows
### Notes au sujet de Windows Phone 7 et 8
* Il n'y a aucune fonction intégrée au navigateur pour `window.confirm`, mais vous pouvez en lier une en affectant:
window.confirm = navigator.notification.confirm ;
* Les appels à `alert` et `confirm` sont non-bloquants, donc le résultat est seulement disponible de façon asynchrone.
### Bizarreries de Windows
* Sur Windows8/8.1, il n'est pas possible d'ajouter plus de trois boutons à MessageDialog instance.
* Sur Windows Phone 8.1, il n'est pas possible d'établir le dialogue avec plus de deux boutons.
### Firefox OS Quirks :
Les deux indigènes bloquant `window.confirm()` et non-bloquante `navigator.notification.confirm()` sont disponibles.
## navigator.notification.prompt
Affiche une boîte de dialogue natif qui est plus personnalisable que le navigateur `prompt` fonction.
Navigator.notification.prompt (message, promptCallback, [title], [buttonLabels], [defaultText])
* **message**: message de la boîte de dialogue. *(String)*
* **promptCallback**: rappel d'invoquer avec l'index du bouton pressé (1, 2 ou 3) ou lorsque la boîte de dialogue est fermée sans une presse de bouton (0). *(Fonction)*
* **titre**: titre *(String)* (facultatif, la valeur par défaut de dialogue`Prompt`)
* **buttonLabels**: tableau de chaînes spécifiant les bouton *(Array)* (facultatif, par défaut, les étiquettes`["OK","Cancel"]`)
* **defaultText**: zone de texte par défaut entrée valeur ( `String` ) (en option, par défaut : chaîne vide)
### promptCallback
Le `promptCallback` s'exécute lorsque l'utilisateur appuie sur un bouton dans la boîte de dialogue d'invite. Le `results` objet passé au rappel contient les propriétés suivantes :
* **buttonIndex**: l'index du bouton activé. *(Nombre)* Notez que l'index utilise base d'indexation, la valeur est `1` , `2` , `3` , etc..
* **entrée 1**: le texte entré dans la boîte de dialogue d'invite. *(String)*
### Exemple
function onPrompt(results) {alert (« Vous avez sélectionné le numéro du bouton » + results.buttonIndex + « et saisi » + results.input1);}
Navigator.notification.prompt ('Veuillez saisir votre nom', / / message onPrompt, / / rappel à appeler « Registration », / / title ['Ok', 'Exit'], / / buttonLabels « Jane Doe » / / defaultText) ;
### Plates-formes supportées
* Amazon Fire OS
* Android
* Firefox OS
* iOS
* Windows Phone 7 et 8
* Windows 8
* Windows
### Quirks Android
* Android prend en charge un maximum de trois boutons et ignore plus que cela.
* Sur Android 3.0 et versions ultérieures, les boutons sont affichés dans l'ordre inverse pour les appareils qui utilisent le thème Holo.
### Bizarreries de Windows
* Sous Windows, dialogue d'invite est basé sur html en raison de l'absence de ces api native.
### Firefox OS Quirks :
Les deux indigènes bloquant `window.prompt()` et non-bloquante `navigator.notification.prompt()` sont disponibles.
## navigator.notification.beep
Le dispositif joue un bip sonore.
Navigator.notification.Beep(Times) ;
* **temps**: le nombre de fois répéter le bip. *(Nombre)*
### Exemple
Deux bips !
Navigator.notification.Beep(2) ;
### Plates-formes supportées
* Amazon Fire OS
* Android
* BlackBerry 10
* iOS
* Paciarelli
* Windows Phone 7 et 8
* Windows 8
### Amazon Fire OS Quirks
* Amazon Fire OS joue la valeur par défaut le **Son de Notification** spécifié sous le panneau **d'affichage des réglages/& Sound** .
### Quirks Android
* Android joue la **sonnerie de Notification** spécifié sous le panneau des **réglages/son et affichage** de valeur par défaut.
### Notes au sujet de Windows Phone 7 et 8
* S'appuie sur un fichier générique bip de la distribution de Cordova.
### Bizarreries de paciarelli
* Paciarelli implémente les bips en lisant un fichier audio via les médias API.
* Le fichier sonore doit être court, doit se trouver dans un `sounds` sous-répertoire du répertoire racine de l'application et doit être nommé`beep.wav`.

View File

@@ -0,0 +1,247 @@
<!---
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# cordova-plugin-dialogs
Ce plugin permet d'accéder à certains éléments d'interface utilisateur native de dialogue via un global `navigator.notification` objet.
Bien que l'objet est attaché à la portée globale `navigator` , il n'est pas disponible jusqu'après la `deviceready` événement.
document.addEventListener (« deviceready », onDeviceReady, false) ;
function onDeviceReady() {console.log(navigator.notification);}
## Installation
Cordova plugin ajouter cordova-plugin-dialogs
## Méthodes
* `navigator.notification.alert`
* `navigator.notification.confirm`
* `navigator.notification.prompt`
* `navigator.notification.beep`
## navigator.notification.alert
Affiche une boîte de dialogue ou d'alerte personnalisé. La plupart des implémentations de Cordova utilisent une boîte de dialogue natives pour cette fonctionnalité, mais certaines plates-formes du navigateur `alert` fonction, qui est généralement moins personnalisable.
Navigator.notification.Alert (message, alertCallback, [title], [buttonName])
* **message**: message de la boîte de dialogue. *(String)*
* **alertCallback**: callback à appeler lorsque la boîte de dialogue d'alerte est rejetée. *(Fonction)*
* **titre**: titre de la boîte de dialogue. *(String)* (Facultatif, par défaut`Alert`)
* **buttonName**: nom du bouton. *(String)* (Facultatif, par défaut`OK`)
### Exemple
function alertDismissed() {/ / faire quelque chose} navigator.notification.alert ('Vous êtes le gagnant!', / / message alertDismissed, / / rappel « Game Over », / / titre « Done » / / buttonName) ;
### Plates-formes prises en charge
* Amazon Fire OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 et 8
* Windows 8
* Windows
### Windows Phone 7 et 8 Quirks
* Il n'y a aucune boîte de dialogue d'alerte intégrée au navigateur, mais vous pouvez en lier une pour appeler `alert()` dans le scope global:
window.alert = navigator.notification.alert;
* Les deux appels `alert` et `confirm` sont non-blocants, leurs résultats ne sont disponibles que de façon asynchrone.
### Firefox OS Quirks :
Les deux indigènes bloquant `window.alert()` et non-bloquante `navigator.notification.alert()` sont disponibles.
### BlackBerry 10 Quirks
`navigator.notification.alert('text', callback, 'title', 'text')`paramètre callback est passé numéro 1.
## navigator.notification.confirm
Affiche une boîte de dialogue de confirmation personnalisable.
Navigator.notification.Confirm (message, confirmCallback, [title], [buttonLabels])
* **message**: message de la boîte de dialogue. *(String)*
* **confirmCallback**: callback à appeler avec l'index du bouton pressé (1, 2 ou 3) ou lorsque la boîte de dialogue est fermée sans qu'un bouton ne soit pressé (0). *(Fonction)*
* **titre**: titre de dialogue. *(String)* (Facultatif, par défaut`Confirm`)
* **buttonLabels**: tableau de chaînes spécifiant les étiquettes des boutons. *(Array)* (Optionnel, par défaut, [ `OK,Cancel` ])
### confirmCallback
Le `confirmCallback` s'exécute lorsque l'utilisateur appuie sur un bouton dans la boîte de dialogue de confirmation.
Le rappel prend l'argument `buttonIndex` *(nombre)*, qui est l'index du bouton activé. Notez que l'index utilise base d'indexation, la valeur est `1` , `2` , `3` , etc..
### Exemple
function onConfirm(buttonIndex) {alert (« Vous bouton sélectionné » + buttonIndex);}
Navigator.notification.Confirm ('Vous êtes le gagnant!', / / message onConfirm, / / rappel d'invoquer avec l'index du bouton enfoncé « Game Over », / / title ['redémarrer', « Exit »] / / buttonLabels) ;
### Plates-formes prises en charge
* Amazon Fire OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Paciarelli
* Windows Phone 7 et 8
* Windows 8
* Windows
### Windows Phone 7 et 8 Quirks
* Il n'y a aucune fonction intégrée au navigateur pour `window.confirm`, mais vous pouvez en lier une en affectant:
window.confirm = navigator.notification.confirm ;
* Les appels à `alert` et `confirm` sont non-bloquants, donc le résultat est seulement disponible de façon asynchrone.
### Bizarreries de Windows
* Sur Windows8/8.1, il n'est pas possible d'ajouter plus de trois boutons à MessageDialog instance.
* Sur Windows Phone 8.1, il n'est pas possible d'établir le dialogue avec plus de deux boutons.
### Firefox OS Quirks :
Les deux indigènes bloquant `window.confirm()` et non-bloquante `navigator.notification.confirm()` sont disponibles.
## navigator.notification.prompt
Affiche une boîte de dialogue natif qui est plus personnalisable que le navigateur `prompt` fonction.
Navigator.notification.prompt (message, promptCallback, [title], [buttonLabels], [defaultText])
* **message**: message de la boîte de dialogue. *(String)*
* **promptCallback**: rappel d'invoquer avec l'index du bouton pressé (1, 2 ou 3) ou lorsque la boîte de dialogue est fermée sans une presse de bouton (0). *(Fonction)*
* **titre**: titre *(String)* (facultatif, la valeur par défaut de dialogue`Prompt`)
* **buttonLabels**: tableau de chaînes spécifiant les bouton *(Array)* (facultatif, par défaut, les étiquettes`["OK","Cancel"]`)
* **defaultText**: zone de texte par défaut entrée valeur ( `String` ) (en option, par défaut : chaîne vide)
### promptCallback
Le `promptCallback` s'exécute lorsque l'utilisateur appuie sur un bouton dans la boîte de dialogue d'invite. Le `results` objet passé au rappel contient les propriétés suivantes :
* **buttonIndex**: l'index du bouton activé. *(Nombre)* Notez que l'index utilise base d'indexation, la valeur est `1` , `2` , `3` , etc..
* **entrée 1**: le texte entré dans la boîte de dialogue d'invite. *(String)*
### Exemple
function onPrompt(results) {alert (« Vous avez sélectionné le numéro du bouton » + results.buttonIndex + « et saisi » + results.input1);}
Navigator.notification.prompt ('Veuillez saisir votre nom', / / message onPrompt, / / rappel à appeler « Registration », / / title ['Ok', 'Exit'], / / buttonLabels « Jane Doe » / / defaultText) ;
### Plates-formes prises en charge
* Amazon Fire OS
* Android
* Firefox OS
* iOS
* Windows Phone 7 et 8
* Windows 8
* Windows
### Quirks Android
* Android prend en charge un maximum de trois boutons et ignore plus que cela.
* Sur Android 3.0 et versions ultérieures, les boutons sont affichés dans l'ordre inverse pour les appareils qui utilisent le thème Holo.
### Bizarreries de Windows
* Sous Windows, dialogue d'invite est basé sur html en raison de l'absence de ces api native.
### Firefox OS Quirks :
Les deux indigènes bloquant `window.prompt()` et non-bloquante `navigator.notification.prompt()` sont disponibles.
## navigator.notification.beep
Le dispositif joue un bip sonore.
Navigator.notification.Beep(Times) ;
* **temps**: le nombre de fois répéter le bip. *(Nombre)*
### Exemple
Deux bips !
Navigator.notification.Beep(2) ;
### Plates-formes prises en charge
* Amazon Fire OS
* Android
* BlackBerry 10
* iOS
* Paciarelli
* Windows Phone 7 et 8
* Windows 8
### Amazon Fire OS Quirks
* Amazon Fire OS joue la valeur par défaut le **Son de Notification** spécifié sous le panneau **d'affichage des réglages/& Sound** .
### Quirks Android
* Android joue la **sonnerie de Notification** spécifié sous le panneau des **réglages/son et affichage** de valeur par défaut.
### Windows Phone 7 et 8 Quirks
* S'appuie sur un fichier générique bip de la distribution de Cordova.
### Bizarreries de paciarelli
* Paciarelli implémente les bips en lisant un fichier audio via les médias API.
* Le fichier sonore doit être court, doit se trouver dans un `sounds` sous-répertoire du répertoire racine de l'application et doit être nommé`beep.wav`.

View File

@@ -0,0 +1,275 @@
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-dialogs
[![Build Status](https://travis-ci.org/apache/cordova-plugin-dialogs.svg)](https://travis-ci.org/apache/cordova-plugin-dialogs)
Questo plugin consente di accedere ad alcuni elementi di interfaccia utente nativa dialogo tramite un oggetto globale `navigator.notification`.
Anche se l'oggetto è associato con ambito globale del `navigator`, non è disponibile fino a dopo l'evento `deviceready`.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.notification);
}
## Installazione
cordova plugin add cordova-plugin-dialogs
## Metodi
* `navigator.notification.alert`
* `navigator.notification.confirm`
* `navigator.notification.prompt`
* `navigator.notification.beep`
## navigator.notification.alert
Mostra una finestra di avviso o la finestra di dialogo personalizzata. La maggior parte delle implementazioni di Cordova utilizzano una finestra di dialogo nativa per questa caratteristica, ma alcune piattaforme utilizzano la funzione di `alert` del browser, che è in genere meno personalizzabile.
navigator.notification.alert(message, alertCallback, [title], [buttonName])
* **message**: messaggio finestra di dialogo. *(String)*
* **alertCallback**: Callback da richiamare quando viene chiusa la finestra di avviso. *(Funzione)*
* **title**: titolo di dialogo. *(String)* (Opzionale, default è `Alert`)
* **buttonName**: nome del pulsante. *(String)* (Opzionale, default è `OK`)
### Esempio
function alertDismissed() {
// do something
}
navigator.notification.alert(
'You are the winner!', // message
alertDismissed, // callback
'Game Over', // title
'Done' // buttonName
);
### Piattaforme supportate
* Amazon fuoco OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 e 8
* Windows 8
* Windows
### Windows Phone 7 e 8 stranezze
* Non non c'è nessun avviso del browser integrato, ma è possibile associare uno come segue per chiamare `alert()` in ambito globale:
window.alert = navigator.notification.alert;
* Entrambi `alert` e `confirm` sono non di blocco chiamate, risultati di cui sono disponibili solo in modo asincrono.
### Firefox OS Stranezze:
Nativo di blocco `window.alert()` blocco `navigator.notification.alert()` sono disponibili sia.
### BlackBerry 10 capricci
parametro di callback `navigator.notification.alert ('text' callback, 'title' 'text')` viene passato il numero 1.
## navigator.notification.confirm
Visualizza una finestra di dialogo conferma personalizzabile.
navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels])
* **message**: messaggio finestra di dialogo. *(String)*
* **confirmCallback**: Callback da richiamare con l'indice del pulsante premuto (1, 2 o 3) o quando la finestra di dialogo viene chiusa senza una pressione del pulsante (0). *(Funzione)*
* **titolo**: titolo di dialogo. *(String)* (Opzionale, default è`Confirm`)
* **buttonLabels**: matrice di stringhe che specificano le etichette dei pulsanti. *(Matrice)* (Opzionale, default è [ `OK,Cancel` ])
### confirmCallback
Il `confirmCallback` viene eseguito quando l'utente preme uno dei pulsanti nella finestra di dialogo conferma.
Il callback accetta l'argomento `buttonIndex` *(numero)*, che è l'indice del pulsante premuto. Si noti che l'indice utilizza l'indicizzazione base uno, quindi il valore è `1`, `2`, `3`, ecc.
### Esempio
function onConfirm(buttonIndex) {
alert('You selected button ' + buttonIndex);
}
navigator.notification.confirm(
'You are the winner!', // message
onConfirm, // callback to invoke with index of button pressed
'Game Over', // title
['Restart','Exit'] // buttonLabels
);
### Piattaforme supportate
* Amazon fuoco OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 e 8
* Windows 8
* Windows
### Windows Phone 7 e 8 stranezze
* Non non c'è nessuna funzione browser incorporato per `window.confirm` , ma è possibile associare assegnando:
window.confirm = navigator.notification.confirm;
* Chiama al `alert` e `confirm` sono non bloccante, quindi il risultato è disponibile solo in modo asincrono.
### Stranezze di Windows
* Su Windows8/8.1 non è possibile aggiungere più di tre pulsanti a MessageDialog istanza.
* Su Windows Phone 8.1 non è possibile mostrare la finestra di dialogo con più di due pulsanti.
### Firefox OS Stranezze:
Nativo di blocco `window.confirm()` blocco `navigator.notification.confirm()` sono disponibili sia.
## navigator.notification.prompt
Visualizza una finestra di dialogo nativa che è più personalizzabile di funzione `prompt` del browser.
navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText])
* **message**: messaggio finestra di dialogo. *(String)*
* **promptCallback**: Callback da richiamare con l'indice del pulsante premuto (1, 2 o 3) o quando la finestra di dialogo viene chiusa senza una pressione del pulsante (0). *(Funzione)*
* **title**: dialogo titolo *(String)* (opzionale, default è `Prompt`)
* **buttonLabels**: matrice di stringhe specificando il pulsante etichette *(Array)* (opzionale, default è `["OK", "Cancel"]`)
* **defaultText**: valore (`String`) di input predefinito textbox (opzionale, Default: empty string)
### promptCallback
Il `promptCallback` viene eseguito quando l'utente preme uno dei pulsanti nella finestra di dialogo richiesta. `results` oggetto passato al metodo di callback contiene le seguenti proprietà:
* **buttonIndex**: l'indice del pulsante premuto. *(Numero)* Si noti che l'indice utilizza l'indicizzazione base uno, quindi il valore è `1`, `2`, `3`, ecc.
* **input1**: il testo immesso nella finestra di dialogo richiesta. *(String)*
### Esempio
function onPrompt(results) {
alert("You selected button number " + results.buttonIndex + " and entered " + results.input1);
}
navigator.notification.prompt(
'Please enter your name', // message
onPrompt, // callback to invoke
'Registration', // title
['Ok','Exit'], // buttonLabels
'Jane Doe' // defaultText
);
### Piattaforme supportate
* Amazon fuoco OS
* Android
* Firefox OS
* iOS
* Windows Phone 7 e 8
* Windows 8
* Windows
### Stranezze Android
* Android supporta un massimo di tre pulsanti e ignora di più di quello.
* Su Android 3.0 e versioni successive, i pulsanti vengono visualizzati in ordine inverso per dispositivi che utilizzano il tema Holo.
### Stranezze di Windows
* Su Windows finestra di dialogo richiesta è a causa di mancanza di tali api nativa basata su html.
### Firefox OS Stranezze:
Nativo di blocco `window.prompt()` blocco `navigator.notification.prompt()` sono disponibili sia.
## navigator.notification.beep
Il dispositivo riproduce un bip sonoro.
navigator.notification.beep(times);
* **times**: il numero di volte per ripetere il segnale acustico. *(Numero)*
### Esempio
// Beep twice!
navigator.notification.beep(2);
### Piattaforme supportate
* Amazon fuoco OS
* Android
* BlackBerry 10
* iOS
* Tizen
* Windows Phone 7 e 8
* Windows 8
### Amazon fuoco OS stranezze
* Amazon fuoco OS riproduce il **Suono di notifica** specificato sotto il pannello **Impostazioni/Display e il suono** predefinito.
### Stranezze Android
* Android giochi default **Notification ringtone** specificato sotto il pannello **impostazioni/audio e Display**.
### Windows Phone 7 e 8 stranezze
* Si basa su un file generico bip dalla distribuzione di Cordova.
### Tizen stranezze
* Tizen implementa bip di riproduzione di un file audio tramite i media API.
* Il file beep deve essere breve, deve trovarsi in una sottodirectory di `sounds` della directory principale dell'applicazione e deve essere denominato `beep.wav`.

View File

@@ -0,0 +1,273 @@
<!---
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# cordova-plugin-dialogs
Questo plugin consente di accedere ad alcuni elementi di interfaccia utente nativa dialogo tramite un oggetto globale `navigator.notification`.
Anche se l'oggetto è associato con ambito globale del `navigator`, non è disponibile fino a dopo l'evento `deviceready`.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.notification);
}
## Installazione
cordova plugin add cordova-plugin-dialogs
## Metodi
* `navigator.notification.alert`
* `navigator.notification.confirm`
* `navigator.notification.prompt`
* `navigator.notification.beep`
## navigator.notification.alert
Mostra una finestra di avviso o la finestra di dialogo personalizzata. La maggior parte delle implementazioni di Cordova utilizzano una finestra di dialogo nativa per questa caratteristica, ma alcune piattaforme utilizzano la funzione di `alert` del browser, che è in genere meno personalizzabile.
navigator.notification.alert(message, alertCallback, [title], [buttonName])
* **message**: messaggio finestra di dialogo. *(String)*
* **alertCallback**: Callback da richiamare quando viene chiusa la finestra di avviso. *(Funzione)*
* **title**: titolo di dialogo. *(String)* (Opzionale, default è `Alert`)
* **buttonName**: nome del pulsante. *(String)* (Opzionale, default è `OK`)
### Esempio
function alertDismissed() {
// do something
}
navigator.notification.alert(
'You are the winner!', // message
alertDismissed, // callback
'Game Over', // title
'Done' // buttonName
);
### Piattaforme supportate
* Amazon fuoco OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 e 8
* Windows 8
* Windows
### Windows Phone 7 e 8 stranezze
* Non non c'è nessun avviso del browser integrato, ma è possibile associare uno come segue per chiamare `alert()` in ambito globale:
window.alert = navigator.notification.alert;
* Entrambi `alert` e `confirm` sono non di blocco chiamate, risultati di cui sono disponibili solo in modo asincrono.
### Firefox OS Stranezze:
Nativo di blocco `window.alert()` blocco `navigator.notification.alert()` sono disponibili sia.
### BlackBerry 10 capricci
parametro di callback `navigator.notification.alert ('text' callback, 'title' 'text')` viene passato il numero 1.
## navigator.notification.confirm
Visualizza una finestra di dialogo conferma personalizzabile.
navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels])
* **messaggio**: messaggio finestra di dialogo. *(String)*
* **confirmCallback**: Callback da richiamare con l'indice del pulsante premuto (1, 2 o 3) o quando la finestra di dialogo viene chiusa senza una pressione del pulsante (0). *(Funzione)*
* **titolo**: titolo di dialogo. *(String)* (Opzionale, default è`Confirm`)
* **buttonLabels**: matrice di stringhe che specificano le etichette dei pulsanti. *(Matrice)* (Opzionale, default è [ `OK,Cancel` ])
### confirmCallback
Il `confirmCallback` viene eseguito quando l'utente preme uno dei pulsanti nella finestra di dialogo conferma.
Il callback accetta l'argomento `buttonIndex` *(numero)*, che è l'indice del pulsante premuto. Si noti che l'indice utilizza l'indicizzazione base uno, quindi il valore è `1`, `2`, `3`, ecc.
### Esempio
function onConfirm(buttonIndex) {
alert('You selected button ' + buttonIndex);
}
navigator.notification.confirm(
'You are the winner!', // message
onConfirm, // callback to invoke with index of button pressed
'Game Over', // title
['Restart','Exit'] // buttonLabels
);
### Piattaforme supportate
* Amazon fuoco OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 e 8
* Windows 8
* Windows
### Windows Phone 7 e 8 stranezze
* Non non c'è nessuna funzione browser incorporato per `window.confirm` , ma è possibile associare assegnando:
window.confirm = navigator.notification.confirm;
* Chiama al `alert` e `confirm` sono non bloccante, quindi il risultato è disponibile solo in modo asincrono.
### Stranezze di Windows
* Su Windows8/8.1 non è possibile aggiungere più di tre pulsanti a MessageDialog istanza.
* Su Windows Phone 8.1 non è possibile mostrare la finestra di dialogo con più di due pulsanti.
### Firefox OS Stranezze:
Nativo di blocco `window.confirm()` blocco `navigator.notification.confirm()` sono disponibili sia.
## navigator.notification.prompt
Visualizza una finestra di dialogo nativa che è più personalizzabile di funzione `prompt` del browser.
navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText])
* **message**: messaggio finestra di dialogo. *(String)*
* **promptCallback**: Callback da richiamare con l'indice del pulsante premuto (1, 2 o 3) o quando la finestra di dialogo viene chiusa senza una pressione del pulsante (0). *(Funzione)*
* **title**: dialogo titolo *(String)* (opzionale, default è `Prompt`)
* **buttonLabels**: matrice di stringhe specificando il pulsante etichette *(Array)* (opzionale, default è `["OK", "Cancel"]`)
* **defaultText**: valore (`String`) di input predefinito textbox (opzionale, Default: empty string)
### promptCallback
Il `promptCallback` viene eseguito quando l'utente preme uno dei pulsanti nella finestra di dialogo richiesta. `results` oggetto passato al metodo di callback contiene le seguenti proprietà:
* **buttonIndex**: l'indice del pulsante premuto. *(Numero)* Si noti che l'indice utilizza l'indicizzazione base uno, quindi il valore è `1`, `2`, `3`, ecc.
* **input1**: il testo immesso nella finestra di dialogo richiesta. *(String)*
### Esempio
function onPrompt(results) {
alert("You selected button number " + results.buttonIndex + " and entered " + results.input1);
}
navigator.notification.prompt(
'Please enter your name', // message
onPrompt, // callback to invoke
'Registration', // title
['Ok','Exit'], // buttonLabels
'Jane Doe' // defaultText
);
### Piattaforme supportate
* Amazon fuoco OS
* Android
* Firefox OS
* iOS
* Windows Phone 7 e 8
* Windows 8
* Windows
### Stranezze Android
* Android supporta un massimo di tre pulsanti e ignora di più di quello.
* Su Android 3.0 e versioni successive, i pulsanti vengono visualizzati in ordine inverso per dispositivi che utilizzano il tema Holo.
### Stranezze di Windows
* Su Windows finestra di dialogo richiesta è a causa di mancanza di tali api nativa basata su html.
### Firefox OS Stranezze:
Nativo di blocco `window.prompt()` blocco `navigator.notification.prompt()` sono disponibili sia.
## navigator.notification.beep
Il dispositivo riproduce un bip sonoro.
navigator.notification.beep(times);
* **times**: il numero di volte per ripetere il segnale acustico. *(Numero)*
### Esempio
// Beep twice!
navigator.notification.beep(2);
### Piattaforme supportate
* Amazon fuoco OS
* Android
* BlackBerry 10
* iOS
* Tizen
* Windows Phone 7 e 8
* Windows 8
### Amazon fuoco OS stranezze
* Amazon fuoco OS riproduce il **Suono di notifica** specificato sotto il pannello **Impostazioni/Display e il suono** predefinito.
### Stranezze Android
* Android giochi default **Notification ringtone** specificato sotto il pannello **impostazioni/audio e Display**.
### Windows Phone 7 e 8 stranezze
* Si basa su un file generico bip dalla distribuzione di Cordova.
### Tizen stranezze
* Tizen implementa bip di riproduzione di un file audio tramite i media API.
* Il file beep deve essere breve, deve trovarsi in una sottodirectory di `sounds` della directory principale dell'applicazione e deve essere denominato `beep.wav`.

View File

@@ -0,0 +1,275 @@
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-dialogs
[![Build Status](https://travis-ci.org/apache/cordova-plugin-dialogs.svg)](https://travis-ci.org/apache/cordova-plugin-dialogs)
このプラグインは、グローバル `navigator.notification` オブジェクトを介していくつかネイティブ ダイアログの UI 要素へのアクセスを提供します。
オブジェクトは、グローバル スコープの `ナビゲーター` に添付、それがないまで `deviceready` イベントの後。
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.notification);
}
## インストール
cordova plugin add cordova-plugin-dialogs
## メソッド
* `navigator.notification.alert`
* `navigator.notification.confirm`
* `navigator.notification.prompt`
* `navigator.notification.beep`
## navigator.notification.alert
カスタムの警告またはダイアログ ボックスが表示されます。 ほとんどコルドバ ネイティブ] ダイアログ ボックスの使用この機能がいくつかのプラットフォームは通常小さいカスタマイズ可能なブラウザーの `警告` 機能を使用します。
navigator.notification.alert(message, alertCallback, [title], [buttonName])
* **メッセージ**: ダイアログ メッセージ。*(文字列)*
* **alertCallback**: 警告ダイアログが閉じられたときに呼び出すコールバック。*(機能)*
* **タイトル**: ダイアログのタイトル。*(文字列)*(省略可能、既定値は`Alert`)
* **buttonName**: ボタンの名前。*(文字列)*(省略可能、既定値は`OK`)
### 例
function alertDismissed() {
// do something
}
navigator.notification.alert(
'You are the winner!', // message
alertDismissed, // callback
'Game Over', // title
'Done' // buttonName
);
### サポートされているプラットフォーム
* アマゾン火 OS
* アンドロイド
* ブラックベリー 10
* Firefox の OS
* iOS
* Tizen
* Windows Phone 7 と 8
* Windows 8
* Windows
### Windows Phone 7 と 8 癖
* 組み込みのブラウザー警告がない呼び出しを次のように 1 つをバインドすることができます `alert()` 、グローバル スコープで。
window.alert = navigator.notification.alert;
* 両方の `alert``confirm` は非ブロッキング呼び出し、結果は非同期的にのみ利用できます。
### Firefox OS 互換:
ネイティブ ブロック `window.alert()` と非ブロッキング `navigator.notification.alert()` があります。
### ブラックベリー 10 癖
`navigator.notification.alert ('text' コールバック 'title'、'text')` コールバック パラメーターは数 1 に渡されます。
## navigator.notification.confirm
カスタマイズ可能な確認のダイアログ ボックスが表示されます。
navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels])
* **メッセージ**: ダイアログ メッセージ。*(文字列)*
* **confirmCallback**: インデックス (1、2、または 3) を押されたボタンまたはダイアログ ボックスは、ボタンを押す 0 なしに解雇されたときに呼び出すコールバック。*(機能)*
* **タイトル**: ダイアログのタイトル。*(文字列)*(省略可能、既定値は`Confirm`)
* **buttonLabels**: ボタンのラベルを指定する文字列の配列。*(配列)*(省略可能、既定値は [ `OK,Cancel` ])
### confirmCallback
`confirmCallback` は、いずれかの確認ダイアログ ボックスでボタンを押したときに実行します。
コールバックは、引数 `buttonIndex` *(番号)* は、押されたボタンのインデックス。 インデックスがインデックス 1 ベースので、値は `1``2``3` などに注意してください。
### 例
function onConfirm(buttonIndex) {
alert('You selected button ' + buttonIndex);
}
navigator.notification.confirm(
'You are the winner!', // message
onConfirm, // callback to invoke with index of button pressed
'Game Over', // title
['Restart','Exit'] // buttonLabels
);
### サポートされているプラットフォーム
* アマゾン火 OS
* アンドロイド
* ブラックベリー 10
* Firefox の OS
* iOS
* Tizen
* Windows Phone 7 と 8
* Windows 8
* Windows
### Windows Phone 7 と 8 癖
* 組み込みブラウザーの機能はありません `window.confirm` が割り当てることによってバインドすることができます。
window.confirm = navigator.notification.confirm;
* 呼び出しを `alert``confirm` では非ブロッキング、結果は非同期的にのみ使用できます。
### Windows の癖
* Windows8/8.1 の MessageDialog インスタンスを 3 つ以上のボタンを追加することはできません。
* Windows Phone 8.1 に 2 つ以上のボタンを持つダイアログを表示することはできません。
### Firefox OS 互換:
ネイティブ ブロック `window.confirm()` と非ブロッキング `navigator.notification.confirm()` があります。
## navigator.notification.prompt
ブラウザーの `プロンプト` 機能より詳細にカスタマイズはネイティブのダイアログ ボックスが表示されます。
navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText])
* **メッセージ**: ダイアログ メッセージ。*(文字列)*
* **promptCallback**: インデックス (1、2、または 3) を押されたボタンまたはダイアログ ボックスは、ボタンを押す 0 なしに解雇されたときに呼び出すコールバック。*(機能)*
* **title**: タイトル *(String)* (省略可能、既定 `プロンプト` ダイアログ)
* **buttonLabels**: ボタンのラベル *(配列)* (省略可能、既定値 `["OK"、「キャンセル」]` を指定する文字列の配列)
* **defaultText**: 既定テキスト ボックスの入力値 (`文字列`) (省略可能、既定: 空の文字列)
### promptCallback
`promptCallback` は、プロンプト ダイアログ ボックス内のボタンのいずれかを押したときに実行します。コールバックに渡される `results` オブジェクトには、次のプロパティが含まれています。
* **buttonIndex**: 押されたボタンのインデックス。*(数)*インデックスがインデックス 1 ベースので、値は `1``2``3` などに注意してください。
* **input1**: プロンプト ダイアログ ボックスに入力したテキスト。*(文字列)*
### 例
function onPrompt(results) {
alert("You selected button number " + results.buttonIndex + " and entered " + results.input1);
}
navigator.notification.prompt(
'Please enter your name', // message
onPrompt, // callback to invoke
'Registration', // title
['Ok','Exit'], // buttonLabels
'Jane Doe' // defaultText
);
### サポートされているプラットフォーム
* アマゾン火 OS
* アンドロイド
* Firefox の OS
* iOS
* Windows Phone 7 と 8
* Windows 8
* Windows
### Android の癖
* Android は最大 3 つのボタンをサポートしているし、それ以上無視します。
* アンドロイド 3.0 と後、ホロのテーマを使用するデバイスを逆の順序でボタンが表示されます。
### Windows の癖
* Windows プロンプト ダイアログは html ベースのようなネイティブ api の不足のためです。
### Firefox OS 互換:
ネイティブ ブロック `window.prompt()` と非ブロッキング `navigator.notification.prompt()` があります。
## navigator.notification.beep
デバイス サウンドをビープ音を再生します。
navigator.notification.beep(times);
* **times**: ビープ音を繰り返す回数。*(数)*
### 例
// Beep twice!
navigator.notification.beep(2);
### サポートされているプラットフォーム
* アマゾン火 OS
* アンドロイド
* ブラックベリー 10
* iOS
* Tizen
* Windows Phone 7 と 8
* Windows 8
### アマゾン火 OS 癖
* アマゾン火 OS デフォルト **設定/表示 サウンド** パネルの下に指定した **通知音** を果たしています。
### Android の癖
* アンドロイド デフォルト **通知着信音** **設定/サウンド ディスプレイ** パネルの下に指定を果たしています。
### Windows Phone 7 と 8 癖
* コルドバ分布からジェネリック ビープ音ファイルに依存します。
### Tizen の癖
* Tizen は、メディア API 経由でオーディオ ファイルを再生してビープ音を実装します。
* ビープ音ファイル短い、`sounds` アプリケーションのルート ディレクトリのサブディレクトリである必要があり。、`beep.wav` という名前である必要があります。.

View File

@@ -0,0 +1,273 @@
<!---
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# cordova-plugin-dialogs
このプラグインは、グローバル `navigator.notification` オブジェクトを介していくつかネイティブ ダイアログの UI 要素へのアクセスを提供します。
オブジェクトは、グローバル スコープの `ナビゲーター` に添付、それがないまで `deviceready` イベントの後。
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.notification);
}
## インストール
cordova plugin add cordova-plugin-dialogs
## メソッド
* `navigator.notification.alert`
* `navigator.notification.confirm`
* `navigator.notification.prompt`
* `navigator.notification.beep`
## navigator.notification.alert
カスタムの警告またはダイアログ ボックスが表示されます。 ほとんどコルドバ ネイティブ] ダイアログ ボックスの使用この機能がいくつかのプラットフォームは通常小さいカスタマイズ可能なブラウザーの `警告` 機能を使用します。
navigator.notification.alert(message, alertCallback, [title], [buttonName])
* **メッセージ**: ダイアログ メッセージ。*(文字列)*
* **alertCallback**: 警告ダイアログが閉じられたときに呼び出すコールバック。*(機能)*
* **タイトル**: ダイアログのタイトル。*(文字列)*(省略可能、既定値は`Alert`)
* **buttonName**: ボタンの名前。*(文字列)*(省略可能、既定値は`OK`)
### 例
function alertDismissed() {
// do something
}
navigator.notification.alert(
'You are the winner!', // message
alertDismissed, // callback
'Game Over', // title
'Done' // buttonName
);
### サポートされているプラットフォーム
* アマゾン火 OS
* アンドロイド
* ブラックベリー 10
* Firefox の OS
* iOS
* Tizen
* Windows Phone 7 と 8
* Windows 8
* Windows
### Windows Phone 7 と 8 癖
* 組み込みのブラウザー警告がない呼び出しを次のように 1 つをバインドすることができます `alert()` 、グローバル スコープで。
window.alert = navigator.notification.alert;
* 両方の `alert``confirm` は非ブロッキング呼び出し、結果は非同期的にのみ利用できます。
### Firefox OS 互換:
ネイティブ ブロック `window.alert()` と非ブロッキング `navigator.notification.alert()` があります。
### ブラックベリー 10 癖
`navigator.notification.alert ('text' コールバック 'title'、'text')` コールバック パラメーターは数 1 に渡されます。
## navigator.notification.confirm
カスタマイズ可能な確認のダイアログ ボックスが表示されます。
navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels])
* **メッセージ**: ダイアログ メッセージ。*(文字列)*
* **confirmCallback**: インデックス (1、2、または 3) を押されたボタンまたはダイアログ ボックスは、ボタンを押す 0 なしに解雇されたときに呼び出すコールバック。*(機能)*
* **タイトル**: ダイアログのタイトル。*(文字列)*(省略可能、既定値は`Confirm`)
* **buttonLabels**: ボタンのラベルを指定する文字列の配列。*(配列)*(省略可能、既定値は [ `OK,Cancel` ])
### confirmCallback
`confirmCallback` は、いずれかの確認ダイアログ ボックスでボタンを押したときに実行します。
コールバックは、引数 `buttonIndex` *(番号)* は、押されたボタンのインデックス。 インデックスがインデックス 1 ベースので、値は `1``2``3` などに注意してください。
### 例
function onConfirm(buttonIndex) {
alert('You selected button ' + buttonIndex);
}
navigator.notification.confirm(
'You are the winner!', // message
onConfirm, // callback to invoke with index of button pressed
'Game Over', // title
['Restart','Exit'] // buttonLabels
);
### サポートされているプラットフォーム
* アマゾン火 OS
* アンドロイド
* ブラックベリー 10
* Firefox の OS
* iOS
* Tizen
* Windows Phone 7 と 8
* Windows 8
* Windows
### Windows Phone 7 と 8 癖
* 組み込みブラウザーの機能はありません `window.confirm` が割り当てることによってバインドすることができます。
window.confirm = navigator.notification.confirm;
* 呼び出しを `alert``confirm` では非ブロッキング、結果は非同期的にのみ使用できます。
### Windows の癖
* Windows8/8.1 の MessageDialog インスタンスを 3 つ以上のボタンを追加することはできません。
* Windows Phone 8.1 に 2 つ以上のボタンを持つダイアログを表示することはできません。
### Firefox OS 互換:
ネイティブ ブロック `window.confirm()` と非ブロッキング `navigator.notification.confirm()` があります。
## navigator.notification.prompt
ブラウザーの `プロンプト` 機能より詳細にカスタマイズはネイティブのダイアログ ボックスが表示されます。
navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText])
* **message**: ダイアログ メッセージ。*(文字列)*
* **promptCallback**: インデックス (1、2、または 3) を押されたボタンまたはダイアログ ボックスは、ボタンを押す 0 なしに解雇されたときに呼び出すコールバック。*(機能)*
* **title**: タイトル *(String)* (省略可能、既定 `プロンプト` ダイアログ)
* **buttonLabels**: ボタンのラベル *(配列)* (省略可能、既定値 `["OK"、「キャンセル」]` を指定する文字列の配列)
* **defaultText**: 既定テキスト ボックスの入力値 (`文字列`) (省略可能、既定: 空の文字列)
### promptCallback
`promptCallback` は、プロンプト ダイアログ ボックス内のボタンのいずれかを押したときに実行します。コールバックに渡される `results` オブジェクトには、次のプロパティが含まれています。
* **buttonIndex**: 押されたボタンのインデックス。*(数)*インデックスがインデックス 1 ベースので、値は `1``2``3` などに注意してください。
* **input1**: プロンプト ダイアログ ボックスに入力したテキスト。*(文字列)*
### 例
function onPrompt(results) {
alert("You selected button number " + results.buttonIndex + " and entered " + results.input1);
}
navigator.notification.prompt(
'Please enter your name', // message
onPrompt, // callback to invoke
'Registration', // title
['Ok','Exit'], // buttonLabels
'Jane Doe' // defaultText
);
### サポートされているプラットフォーム
* アマゾン火 OS
* アンドロイド
* Firefox の OS
* iOS
* Windows Phone 7 と 8
* Windows 8
* Windows
### Android の癖
* Android は最大 3 つのボタンをサポートしているし、それ以上無視します。
* アンドロイド 3.0 と後、ホロのテーマを使用するデバイスを逆の順序でボタンが表示されます。
### Windows の癖
* Windows プロンプト ダイアログは html ベースのようなネイティブ api の不足のためです。
### Firefox OS 互換:
ネイティブ ブロック `window.prompt()` と非ブロッキング `navigator.notification.prompt()` があります。
## navigator.notification.beep
デバイス サウンドをビープ音を再生します。
navigator.notification.beep(times);
* **times**: ビープ音を繰り返す回数。*(数)*
### 例
// Beep twice!
navigator.notification.beep(2);
### サポートされているプラットフォーム
* アマゾン火 OS
* アンドロイド
* ブラックベリー 10
* iOS
* Tizen
* Windows Phone 7 と 8
* Windows 8
### アマゾン火 OS 癖
* アマゾン火 OS デフォルト **設定/表示 サウンド** パネルの下に指定した **通知音** を果たしています。
### Android の癖
* アンドロイド デフォルト **通知着信音** **設定/サウンド ディスプレイ** パネルの下に指定を果たしています。
### Windows Phone 7 と 8 癖
* コルドバ分布からジェネリック ビープ音ファイルに依存します。
### Tizen の癖
* Tizen は、メディア API 経由でオーディオ ファイルを再生してビープ音を実装します。
* ビープ音ファイル短い、`sounds` アプリケーションのルート ディレクトリのサブディレクトリである必要があり。、`beep.wav` という名前である必要があります。.

View File

@@ -0,0 +1,275 @@
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-dialogs
[![Build Status](https://travis-ci.org/apache/cordova-plugin-dialogs.svg)](https://travis-ci.org/apache/cordova-plugin-dialogs)
이 플러그인 글로벌 `navigator.notification` 개체를 통해 몇 가지 기본 대화 상자 UI 요소에 액세스할 수 있습니다.
개체 `navigator` 글로벌 범위 첨부 아니에요 때까지 사용할 수 있는 `deviceready` 이벤트 후.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.notification);
}
## 설치
cordova plugin add cordova-plugin-dialogs
## 메서드
* `navigator.notification.alert`
* `navigator.notification.confirm`
* `navigator.notification.prompt`
* `navigator.notification.beep`
## navigator.notification.alert
사용자 지정 경고 또는 대화 상자를 보여 줍니다. 이 기능에 대 한 기본 대화 상자를 사용 하는 대부분의 코르도바 구현 하지만 일부 플랫폼은 일반적으로 덜 사용자 정의할 수 있는 브라우저의 `alert` 기능을 사용 합니다.
navigator.notification.alert(message, alertCallback, [title], [buttonName])
* **message**: 대화 메시지. *(문자열)*
* **alertCallback**: 콜백을 호출할 때 경고 대화 기 각. *(기능)*
* **title**: 제목 대화 상자. *(문자열)* (옵션, 기본값:`Alert`)
* **buttonName**: 단추 이름. *(문자열)* (옵션, 기본값:`OK`)
### 예를 들어
function alertDismissed() {
// do something
}
navigator.notification.alert(
'You are the winner!', // message
alertDismissed, // callback
'Game Over', // title
'Done' // buttonName
);
### 지원 되는 플랫폼
* 아마존 화재 운영 체제
* 안 드 로이드
* 블랙베리 10
* Firefox 운영 체제
* iOS
* Tizen
* Windows Phone 7과 8
* 윈도우 8
* 윈도우
### Windows Phone 7, 8 특수
* 아니 내장 브라우저 경고 하지만 다음과 같이 전화를 바인딩할 수 있습니다 `alert()` 전역 범위에서:
window.alert = navigator.notification.alert;
* 둘 다 `alert``confirm` 는 비차단 호출, 결과 비동기적으로 사용할 수 있습니다.
### 파이어 폭스 OS 단점:
기본 차단 `window.alert()` 및 차단 되지 않은 `navigator.notification.alert()` 사용할 수 있습니다.
### 블랙베리 10 단점
`navigator.notification.alert ('텍스트', 콜백, '제목', '텍스트')` 콜백 매개 변수 1 번을 전달 됩니다.
## navigator.notification.confirm
사용자 정의 확인 대화 상자가 표시 됩니다.
navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels])
* **message**: 대화 메시지. *(문자열)*
* **confirmCallback**: 인덱스 버튼 (1, 2 또는 3) 또는 대화 상자 버튼을 누르면 (0) 없이 기 각 될 때 호출할 콜백 합니다. *(기능)*
* **title**: 제목 대화 상자. *(문자열)* (옵션, 기본값:`Confirm`)
* **buttonLabels**: 단추 레이블을 지정 하는 문자열 배열입니다. *(배열)* (옵션, 기본값은 [ `OK,Cancel` ])
### confirmCallback
`confirmCallback`는 사용자가 확인 대화 상자에서 단추 중 하나를 누를 때 실행 합니다.
콜백이 걸립니다 인수 `buttonIndex` *(번호)를* 누르면된 버튼의 인덱스입니다. Note 인덱스에서는 인덱싱 1 시작 값은 `1`, `2`, `3`, 등등.
### 예를 들어
function onConfirm(buttonIndex) {
alert('You selected button ' + buttonIndex);
}
navigator.notification.confirm(
'You are the winner!', // message
onConfirm, // callback to invoke with index of button pressed
'Game Over', // title
['Restart','Exit'] // buttonLabels
);
### 지원 되는 플랫폼
* 아마존 화재 운영 체제
* 안 드 로이드
* 블랙베리 10
* Firefox 운영 체제
* iOS
* Tizen
* Windows Phone 7과 8
* 윈도우 8
* 윈도우
### Windows Phone 7, 8 특수
* 에 대 한 기본 제공 브라우저 함수가 `window.confirm` , 그러나 할당 하 여 바인딩할 수 있습니다:
window.confirm = navigator.notification.confirm;
* 호출 `alert``confirm` 되므로 차단 되지 않은 결과만 비동기적으로 사용할 수 있습니다.
### 윈도우 특수
* Windows8/8.1에 3 개 이상 단추 MessageDialog 인스턴스를 추가할 수는 없습니다.
* Windows Phone 8.1에 두 개 이상의 단추와 대화 상자 표시 수는 없습니다.
### 파이어 폭스 OS 단점:
기본 차단 `window.confirm()` 및 차단 되지 않은 `navigator.notification.confirm()` 사용할 수 있습니다.
## navigator.notification.prompt
브라우저의 `프롬프트` 함수 보다 더 많은 사용자 정의 기본 대화 상자가 표시 됩니다.
navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText])
* **message**: 대화 메시지. *(문자열)*
* **promptCallback**: 인덱스 버튼 (1, 2 또는 3) 또는 대화 상자 버튼을 누르면 (0) 없이 기 각 될 때 호출할 콜백 합니다. *(기능)*
* **title**: 제목 대화 상자. *(문자열)* (옵션, 기본값:`Prompt`)
* **buttonLabels**: 버튼 레이블 *(배열)* (옵션, 기본값 `["확인", "취소"]을` 지정 하는 문자열의 배열)
* **defaultText**: 기본 텍스트 상자에 값 (`문자열`) 입력 (옵션, 기본값: 빈 문자열)
### promptCallback
`promptCallback`는 사용자가 프롬프트 대화 상자에서 단추 중 하나를 누를 때 실행 합니다. 콜백에 전달 된 `results` 개체에는 다음 속성이 포함 되어 있습니다.
* **buttonIndex**: 눌려진된 버튼의 인덱스. *(수)* Note 인덱스에서는 인덱싱 1 시작 값은 `1`, `2`, `3`, 등등.
* **input1**: 프롬프트 대화 상자에 입력 한 텍스트. *(문자열)*
### 예를 들어
function onPrompt(results) {
alert("You selected button number " + results.buttonIndex + " and entered " + results.input1);
}
navigator.notification.prompt(
'Please enter your name', // message
onPrompt, // callback to invoke
'Registration', // title
['Ok','Exit'], // buttonLabels
'Jane Doe' // defaultText
);
### 지원 되는 플랫폼
* 아마존 화재 운영 체제
* 안 드 로이드
* Firefox 운영 체제
* iOS
* Windows Phone 7과 8
* 윈도우 8
* 윈도우
### 안 드 로이드 단점
* 안 드 로이드 최대 3 개의 단추를 지원 하 고 그것 보다는 더 이상 무시 합니다.
* 안 드 로이드 3.0 및 나중에, 단추는 홀로 테마를 사용 하는 장치에 대 한 반대 순서로 표시 됩니다.
### 윈도우 특수
* 윈도우에서 프롬프트 대화 같은 네이티브 api의 부족으로 인해 html 기반 이다.
### 파이어 폭스 OS 단점:
기본 차단 `window.prompt()` 및 차단 되지 않은 `navigator.notification.prompt()` 사용할 수 있습니다.
## navigator.notification.beep
장치는 경고음 소리를 재생 합니다.
navigator.notification.beep(times);
* **times**: 경고음을 반복 하는 횟수. *(수)*
### 예를 들어
// Beep twice!
navigator.notification.beep(2);
### 지원 되는 플랫폼
* 아마존 화재 운영 체제
* 안 드 로이드
* 블랙베리 10
* iOS
* Tizen
* Windows Phone 7과 8
* 윈도우 8
### 아마존 화재 OS 단점
* 아마존 화재 운영 체제 기본 **설정/디스플레이 및 사운드** 패널에 지정 된 **알림 소리** 재생 됩니다.
### 안 드 로이드 단점
* 안 드 로이드 기본 **알림 벨소리** **설정/사운드 및 디스플레이** 패널에서 지정 합니다.
### Windows Phone 7, 8 특수
* 코르 도우 바 분포에서 일반 경고음 파일에 의존합니다.
### Tizen 특수
* Tizen은 미디어 API 통해 오디오 파일을 재생 하 여 경고음을 구현 합니다.
* 경고음 파일 짧은 되어야 합니다, 응용 프로그램의 루트 디렉터리의 `소리` 하위 디렉터리에 위치 해야 합니다 및 `beep.wav`는 명명 된.

View File

@@ -0,0 +1,273 @@
<!---
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# cordova-plugin-dialogs
이 플러그인 글로벌 `navigator.notification` 개체를 통해 몇 가지 기본 대화 상자 UI 요소에 액세스할 수 있습니다.
개체 `navigator` 글로벌 범위 첨부 아니에요 때까지 사용할 수 있는 `deviceready` 이벤트 후.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.notification);
}
## 설치
cordova plugin add cordova-plugin-dialogs
## 메서드
* `navigator.notification.alert`
* `navigator.notification.confirm`
* `navigator.notification.prompt`
* `navigator.notification.beep`
## navigator.notification.alert
사용자 지정 경고 또는 대화 상자를 보여 줍니다. 이 기능에 대 한 기본 대화 상자를 사용 하는 대부분의 코르도바 구현 하지만 일부 플랫폼은 일반적으로 덜 사용자 정의할 수 있는 브라우저의 `alert` 기능을 사용 합니다.
navigator.notification.alert(message, alertCallback, [title], [buttonName])
* **message**: 대화 메시지. *(문자열)*
* **alertCallback**: 콜백을 호출할 때 경고 대화 기 각. *(기능)*
* **title**: 제목 대화 상자. *(문자열)* (옵션, 기본값:`Alert`)
* **buttonName**: 단추 이름. *(문자열)* (옵션, 기본값:`OK`)
### 예를 들어
function alertDismissed() {
// do something
}
navigator.notification.alert(
'You are the winner!', // message
alertDismissed, // callback
'Game Over', // title
'Done' // buttonName
);
### 지원 되는 플랫폼
* 아마존 화재 운영 체제
* 안 드 로이드
* 블랙베리 10
* Firefox 운영 체제
* iOS
* Tizen
* Windows Phone 7과 8
* 윈도우 8
* 윈도우
### Windows Phone 7, 8 특수
* 아니 내장 브라우저 경고 하지만 다음과 같이 전화를 바인딩할 수 있습니다 `alert()` 전역 범위에서:
window.alert = navigator.notification.alert;
* 둘 다 `alert``confirm` 는 비차단 호출, 결과 비동기적으로 사용할 수 있습니다.
### 파이어 폭스 OS 단점:
기본 차단 `window.alert()` 및 차단 되지 않은 `navigator.notification.alert()` 사용할 수 있습니다.
### 블랙베리 10 단점
`navigator.notification.alert ('텍스트', 콜백, '제목', '텍스트')` 콜백 매개 변수 1 번을 전달 됩니다.
## navigator.notification.confirm
사용자 정의 확인 대화 상자가 표시 됩니다.
navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels])
* **message**: 대화 메시지. *(문자열)*
* **confirmCallback**: 인덱스 버튼 (1, 2 또는 3) 또는 대화 상자 버튼을 누르면 (0) 없이 기 각 될 때 호출할 콜백 합니다. *(기능)*
* **title**: 제목 대화 상자. *(문자열)* (옵션, 기본값:`Confirm`)
* **buttonLabels**: 단추 레이블을 지정 하는 문자열 배열입니다. *(배열)* (옵션, 기본값은 [ `OK,Cancel` ])
### confirmCallback
`confirmCallback`는 사용자가 확인 대화 상자에서 단추 중 하나를 누를 때 실행 합니다.
콜백이 걸립니다 인수 `buttonIndex` *(번호)를* 누르면된 버튼의 인덱스입니다. Note 인덱스에서는 인덱싱 1 시작 값은 `1`, `2`, `3`, 등등.
### 예를 들어
function onConfirm(buttonIndex) {
alert('You selected button ' + buttonIndex);
}
navigator.notification.confirm(
'You are the winner!', // message
onConfirm, // callback to invoke with index of button pressed
'Game Over', // title
['Restart','Exit'] // buttonLabels
);
### 지원 되는 플랫폼
* 아마존 화재 운영 체제
* 안 드 로이드
* 블랙베리 10
* Firefox 운영 체제
* iOS
* Tizen
* Windows Phone 7과 8
* 윈도우 8
* 윈도우
### Windows Phone 7, 8 특수
* 에 대 한 기본 제공 브라우저 함수가 `window.confirm` , 그러나 할당 하 여 바인딩할 수 있습니다:
window.confirm = navigator.notification.confirm;
* 호출 `alert``confirm` 되므로 차단 되지 않은 결과만 비동기적으로 사용할 수 있습니다.
### 윈도우 특수
* Windows8/8.1에 3 개 이상 단추 MessageDialog 인스턴스를 추가할 수는 없습니다.
* Windows Phone 8.1에 두 개 이상의 단추와 대화 상자 표시 수는 없습니다.
### 파이어 폭스 OS 단점:
기본 차단 `window.confirm()` 및 차단 되지 않은 `navigator.notification.confirm()` 사용할 수 있습니다.
## navigator.notification.prompt
브라우저의 `프롬프트` 함수 보다 더 많은 사용자 정의 기본 대화 상자가 표시 됩니다.
navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText])
* **message**: 대화 메시지. *(문자열)*
* **promptCallback**: 인덱스 버튼 (1, 2 또는 3) 또는 대화 상자 버튼을 누르면 (0) 없이 기 각 될 때 호출할 콜백 합니다. *(기능)*
* **title**: 제목 대화 상자. *(문자열)* (옵션, 기본값:`Prompt`)
* **buttonLabels**: 버튼 레이블 *(배열)* (옵션, 기본값 `["확인", "취소"]을` 지정 하는 문자열의 배열)
* **defaultText**: 기본 텍스트 상자에 값 (`문자열`) 입력 (옵션, 기본값: 빈 문자열)
### promptCallback
`promptCallback`는 사용자가 프롬프트 대화 상자에서 단추 중 하나를 누를 때 실행 합니다. 콜백에 전달 된 `results` 개체에는 다음 속성이 포함 되어 있습니다.
* **buttonIndex**: 눌려진된 버튼의 인덱스. *(수)* Note 인덱스에서는 인덱싱 1 시작 값은 `1`, `2`, `3`, 등등.
* **input1**: 프롬프트 대화 상자에 입력 한 텍스트. *(문자열)*
### 예를 들어
function onPrompt(results) {
alert("You selected button number " + results.buttonIndex + " and entered " + results.input1);
}
navigator.notification.prompt(
'Please enter your name', // message
onPrompt, // callback to invoke
'Registration', // title
['Ok','Exit'], // buttonLabels
'Jane Doe' // defaultText
);
### 지원 되는 플랫폼
* 아마존 화재 운영 체제
* 안 드 로이드
* Firefox 운영 체제
* iOS
* Windows Phone 7과 8
* 윈도우 8
* 윈도우
### 안 드 로이드 단점
* 안 드 로이드 최대 3 개의 단추를 지원 하 고 그것 보다는 더 이상 무시 합니다.
* 안 드 로이드 3.0 및 나중에, 단추는 홀로 테마를 사용 하는 장치에 대 한 반대 순서로 표시 됩니다.
### 윈도우 특수
* 윈도우에서 프롬프트 대화 같은 네이티브 api의 부족으로 인해 html 기반 이다.
### 파이어 폭스 OS 단점:
기본 차단 `window.prompt()` 및 차단 되지 않은 `navigator.notification.prompt()` 사용할 수 있습니다.
## navigator.notification.beep
장치는 경고음 소리를 재생 합니다.
navigator.notification.beep(times);
* **times**: 경고음을 반복 하는 횟수. *(수)*
### 예를 들어
// Beep twice!
navigator.notification.beep(2);
### 지원 되는 플랫폼
* 아마존 화재 운영 체제
* 안 드 로이드
* 블랙베리 10
* iOS
* Tizen
* Windows Phone 7과 8
* 윈도우 8
### 아마존 화재 OS 단점
* 아마존 화재 운영 체제 기본 **설정/디스플레이 및 사운드** 패널에 지정 된 **알림 소리** 재생 됩니다.
### 안 드 로이드 단점
* 안 드 로이드 기본 **알림 벨소리** **설정/사운드 및 디스플레이** 패널에서 지정 합니다.
### Windows Phone 7, 8 특수
* 코르 도우 바 분포에서 일반 경고음 파일에 의존합니다.
### Tizen 특수
* Tizen은 미디어 API 통해 오디오 파일을 재생 하 여 경고음을 구현 합니다.
* 경고음 파일 짧은 되어야 합니다, 응용 프로그램의 루트 디렉터리의 `소리` 하위 디렉터리에 위치 해야 합니다 및 `beep.wav`는 명명 된.

View File

@@ -0,0 +1,275 @@
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-dialogs
[![Build Status](https://travis-ci.org/apache/cordova-plugin-dialogs.svg)](https://travis-ci.org/apache/cordova-plugin-dialogs)
Ten plugin umożliwia dostęp do niektórych rodzimych okna dialogowego elementy interfejsu użytkownika za pośrednictwem obiektu globalnego `navigator.notification`.
Mimo, że obiekt jest dołączony do globalnego zakresu `navigator`, to nie dostępne dopiero po zdarzeniu `deviceready`.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.notification);
}
## Instalacja
cordova plugin add cordova-plugin-dialogs
## Metody
* `navigator.notification.alert`
* `navigator.notification.confirm`
* `navigator.notification.prompt`
* `navigator.notification.beep`
## navigator.notification.alert
Pokazuje niestandardowe wpisu lub okno dialogowe. Większość implementacji Cordova używać rodzimych okno dialogowe dla tej funkcji, ale niektóre platformy używać przeglądarki `alert` funkcji, która jest zazwyczaj mniej konfigurowalny.
navigator.notification.alert(message, alertCallback, [title], [buttonName])
* **wiadomość**: komunikat okna dialogowego. *(String)*
* **alertCallback**: wywołanie zwrotne do wywołania, gdy okno dialogowe alert jest oddalona. *(Funkcja)*
* **tytuł**: okno tytuł. *(String)* (Opcjonalna, domyślnie`Alert`)
* **buttonName**: Nazwa przycisku. *(String)* (Opcjonalna, domyślnie`OK`)
### Przykład
function alertDismissed() {
// do something
}
navigator.notification.alert(
'You are the winner!', // message
alertDismissed, // callback
'Game Over', // title
'Done' // buttonName
);
### Obsługiwane platformy
* Amazon Fire OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 i 8
* Windows 8
* Windows
### Windows Phone 7 i 8 dziwactwa
* Istnieje wpis nie wbudowana przeglądarka, ale można powiązać w następujący sposób na wywołanie `alert()` w globalnym zasięgu:
window.alert = navigator.notification.alert;
* Zarówno `alert` i `confirm` są bez blokowania połączeń, których wyniki są tylko dostępne asynchronicznie.
### Firefox OS dziwactwa:
Dostępne są zarówno rodzimych blokuje `window.alert()` i bez blokowania `navigator.notification.alert()`.
### Jeżyna 10 dziwactwa
parametr wywołania zwrotnego `Navigator.Notification.alert ("tekst", wywołanie zwrotne, 'tytuł', 'tekst')` jest przekazywana numer 1.
## navigator.notification.confirm
Wyświetla okno dialogowe potwierdzenia konfigurowalny.
navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels])
* **wiadomość**: komunikat okna dialogowego. *(String)*
* **confirmCallback**: wywołanie zwrotne do wywołania z indeksu z przycisku (1, 2 lub 3), lub gdy okno jest zwolniony bez naciśnij przycisk (0). *(Funkcja)*
* **tytuł**: okno tytuł. *(String)* (Opcjonalna, domyślnie`Confirm`)
* **buttonLabels**: tablica ciągów, określając etykiety przycisków. *(Tablica)* (Opcjonalna, domyślnie [ `OK,Cancel` ])
### confirmCallback
`confirmCallback` wykonuje, gdy użytkownik naciśnie klawisz jeden z przycisków w oknie dialogowym potwierdzenia.
Wywołanie zwrotne wymaga argumentu `buttonIndex` *(numer)*, który jest indeksem wciśnięty przycisk. Należy zauważyć, że indeks używa, na podstawie jednego indeksowania, więc wartością jest `1`, `2`, `3` itd.
### Przykład
function onConfirm(buttonIndex) {
alert('You selected button ' + buttonIndex);
}
navigator.notification.confirm(
'You are the winner!', // message
onConfirm, // callback to invoke with index of button pressed
'Game Over', // title
['Restart','Exit'] // buttonLabels
);
### Obsługiwane platformy
* Amazon Fire OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 i 8
* Windows 8
* Windows
### Windows Phone 7 i 8 dziwactwa
* Istnieje funkcja wbudowana przeglądarka nie `window.confirm` , ale można go powiązać przypisując:
window.confirm = navigator.notification.confirm;
* Wzywa do `alert` i `confirm` są bez blokowania, więc wynik jest tylko dostępnych asynchronicznie.
### Windows dziwactwa
* Na Windows8/8.1 to nie można dodać więcej niż trzy przyciski do instancji MessageDialog.
* Na Windows Phone 8.1 nie jest możliwe wyświetlić okno dialogowe z więcej niż dwoma przyciskami.
### Firefox OS dziwactwa:
Dostępne są zarówno rodzimych blokuje `window.confirm()` i bez blokowania `navigator.notification.confirm()`.
## navigator.notification.prompt
Wyświetla okno dialogowe macierzystego, który bardziej niż przeglądarki `prompt` funkcja.
navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText])
* **wiadomość**: komunikat okna dialogowego. *(String)*
* **promptCallback**: wywołanie zwrotne do wywołania z indeksu z przycisku (1, 2 lub 3), lub gdy okno jest zwolniony bez naciśnij przycisk (0). *(Funkcja)*
* **title**: okno tytuł *(String)* (opcjonalna, domyślnie `polecenia`)
* **buttonLabels**: tablica ciągów, określając przycisk etykiety *(tablica)* (opcjonalna, domyślnie `["OK", "Anuluj"]`)
* **defaultText**: domyślnie pole tekstowe wprowadzania wartości (`String`) (opcjonalna, domyślnie: pusty ciąg)
### promptCallback
`promptCallback` wykonuje, gdy użytkownik naciśnie klawisz jeden z przycisków w oknie dialogowym polecenia. Obiektu `results` przekazane do wywołania zwrotnego zawiera następujące właściwości:
* **buttonIndex**: indeks wciśnięty przycisk. *(Liczba)* Należy zauważyć, że indeks używa, na podstawie jednego indeksowania, więc wartością jest `1`, `2`, `3` itd.
* **input1**: Tekst wprowadzony w oknie polecenia. *(String)*
### Przykład
function onPrompt(results) {
alert("You selected button number " + results.buttonIndex + " and entered " + results.input1);
}
navigator.notification.prompt(
'Please enter your name', // message
onPrompt, // callback to invoke
'Registration', // title
['Ok','Exit'], // buttonLabels
'Jane Doe' // defaultText
);
### Obsługiwane platformy
* Amazon Fire OS
* Android
* Firefox OS
* iOS
* Windows Phone 7 i 8
* Windows 8
* Windows
### Dziwactwa Androida
* Android obsługuje maksymalnie trzy przyciski i więcej niż to ignoruje.
* Android 3.0 i nowszych przyciski są wyświetlane w kolejności odwrotnej do urządzenia, które używają tematu Holo.
### Windows dziwactwa
* W systemie Windows wierzyciel okno jest oparte na języku html, ze względu na brak takich natywnego api.
### Firefox OS dziwactwa:
Dostępne są zarówno rodzimych blokuje `window.prompt()` i bez blokowania `navigator.notification.prompt()`.
## navigator.notification.beep
Urządzenie odtwarza sygnał ciągły dźwięk.
navigator.notification.beep(times);
* **times**: liczba powtórzeń po sygnale. *(Liczba)*
### Przykład
// Beep twice!
navigator.notification.beep(2);
### Obsługiwane platformy
* Amazon Fire OS
* Android
* BlackBerry 10
* iOS
* Tizen
* Windows Phone 7 i 8
* Windows 8
### Amazon ogień OS dziwactwa
* Amazon ogień OS gra domyślny **Dźwięk powiadomienia** określone w panelu **ekranu/ustawienia i dźwięk**.
### Dziwactwa Androida
* Android gra domyślnie **dzwonek powiadomienia** określone w panelu **ustawień/dźwięk i wyświetlacz**.
### Windows Phone 7 i 8 dziwactwa
* Opiera się na pliku rodzajowego sygnał z rozkładu Cordova.
### Dziwactwa Tizen
* Tizen implementuje dźwięków przez odtwarzania pliku audio za pośrednictwem mediów API.
* Plik dźwiękowy muszą być krótkie, musi znajdować się w podkatalogu `dźwięki` w katalogu głównym aplikacji i musi być o nazwie `beep.wav`.

View File

@@ -0,0 +1,273 @@
<!---
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# cordova-plugin-dialogs
Ten plugin umożliwia dostęp do niektórych rodzimych okna dialogowego elementy interfejsu użytkownika za pośrednictwem obiektu globalnego `navigator.notification`.
Mimo, że obiekt jest dołączony do globalnego zakresu `navigator`, to nie dostępne dopiero po zdarzeniu `deviceready`.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.notification);
}
## Instalacja
cordova plugin add cordova-plugin-dialogs
## Metody
* `navigator.notification.alert`
* `navigator.notification.confirm`
* `navigator.notification.prompt`
* `navigator.notification.beep`
## navigator.notification.alert
Pokazuje niestandardowe wpisu lub okno dialogowe. Większość implementacji Cordova używać rodzimych okno dialogowe dla tej funkcji, ale niektóre platformy używać przeglądarki `alert` funkcji, która jest zazwyczaj mniej konfigurowalny.
navigator.notification.alert(message, alertCallback, [title], [buttonName])
* **wiadomość**: komunikat okna dialogowego. *(String)*
* **alertCallback**: wywołanie zwrotne do wywołania, gdy okno dialogowe alert jest oddalona. *(Funkcja)*
* **tytuł**: okno tytuł. *(String)* (Opcjonalna, domyślnie`Alert`)
* **buttonName**: Nazwa przycisku. *(String)* (Opcjonalna, domyślnie`OK`)
### Przykład
function alertDismissed() {
// do something
}
navigator.notification.alert(
'You are the winner!', // message
alertDismissed, // callback
'Game Over', // title
'Done' // buttonName
);
### Obsługiwane platformy
* Amazon Fire OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 i 8
* Windows 8
* Windows
### Windows Phone 7 i 8 dziwactwa
* Istnieje wpis nie wbudowana przeglądarka, ale można powiązać w następujący sposób na wywołanie `alert()` w globalnym zasięgu:
window.alert = navigator.notification.alert;
* Zarówno `alert` i `confirm` są bez blokowania połączeń, których wyniki są tylko dostępne asynchronicznie.
### Firefox OS dziwactwa:
Dostępne są zarówno rodzimych blokuje `window.alert()` i bez blokowania `navigator.notification.alert()`.
### Jeżyna 10 dziwactwa
parametr wywołania zwrotnego `Navigator.Notification.alert ("tekst", wywołanie zwrotne, 'tytuł', 'tekst')` jest przekazywana numer 1.
## navigator.notification.confirm
Wyświetla okno dialogowe potwierdzenia konfigurowalny.
navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels])
* **wiadomość**: komunikat okna dialogowego. *(String)*
* **confirmCallback**: wywołanie zwrotne do wywołania z indeksu z przycisku (1, 2 lub 3), lub gdy okno jest zwolniony bez naciśnij przycisk (0). *(Funkcja)*
* **tytuł**: okno tytuł. *(String)* (Opcjonalna, domyślnie`Confirm`)
* **buttonLabels**: tablica ciągów, określając etykiety przycisków. *(Tablica)* (Opcjonalna, domyślnie [ `OK,Cancel` ])
### confirmCallback
`confirmCallback` wykonuje, gdy użytkownik naciśnie klawisz jeden z przycisków w oknie dialogowym potwierdzenia.
Wywołanie zwrotne wymaga argumentu `buttonIndex` *(numer)*, który jest indeksem wciśnięty przycisk. Należy zauważyć, że indeks używa, na podstawie jednego indeksowania, więc wartością jest `1`, `2`, `3` itd.
### Przykład
function onConfirm(buttonIndex) {
alert('You selected button ' + buttonIndex);
}
navigator.notification.confirm(
'You are the winner!', // message
onConfirm, // callback to invoke with index of button pressed
'Game Over', // title
['Restart','Exit'] // buttonLabels
);
### Obsługiwane platformy
* Amazon Fire OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 i 8
* Windows 8
* Windows
### Windows Phone 7 i 8 dziwactwa
* Istnieje funkcja wbudowana przeglądarka nie `window.confirm` , ale można go powiązać przypisując:
window.confirm = navigator.notification.confirm;
* Wzywa do `alert` i `confirm` są bez blokowania, więc wynik jest tylko dostępnych asynchronicznie.
### Windows dziwactwa
* Na Windows8/8.1 to nie można dodać więcej niż trzy przyciski do instancji MessageDialog.
* Na Windows Phone 8.1 nie jest możliwe wyświetlić okno dialogowe z więcej niż dwoma przyciskami.
### Firefox OS dziwactwa:
Dostępne są zarówno rodzimych blokuje `window.confirm()` i bez blokowania `navigator.notification.confirm()`.
## navigator.notification.prompt
Wyświetla okno dialogowe macierzystego, który bardziej niż przeglądarki `prompt` funkcja.
navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText])
* **message**: komunikat okna dialogowego. *(String)*
* **promptCallback**: wywołanie zwrotne do wywołania z indeksu z przycisku (1, 2 lub 3), lub gdy okno jest zwolniony bez naciśnij przycisk (0). *(Funkcja)*
* **title**: okno tytuł *(String)* (opcjonalna, domyślnie `polecenia`)
* **buttonLabels**: tablica ciągów, określając przycisk etykiety *(tablica)* (opcjonalna, domyślnie `["OK", "Anuluj"]`)
* **defaultText**: domyślnie pole tekstowe wprowadzania wartości (`String`) (opcjonalna, domyślnie: pusty ciąg)
### promptCallback
`promptCallback` wykonuje, gdy użytkownik naciśnie klawisz jeden z przycisków w oknie dialogowym polecenia. Obiektu `results` przekazane do wywołania zwrotnego zawiera następujące właściwości:
* **buttonIndex**: indeks wciśnięty przycisk. *(Liczba)* Należy zauważyć, że indeks używa, na podstawie jednego indeksowania, więc wartością jest `1`, `2`, `3` itd.
* **input1**: Tekst wprowadzony w oknie polecenia. *(String)*
### Przykład
function onPrompt(results) {
alert("You selected button number " + results.buttonIndex + " and entered " + results.input1);
}
navigator.notification.prompt(
'Please enter your name', // message
onPrompt, // callback to invoke
'Registration', // title
['Ok','Exit'], // buttonLabels
'Jane Doe' // defaultText
);
### Obsługiwane platformy
* Amazon Fire OS
* Android
* Firefox OS
* iOS
* Windows Phone 7 i 8
* Windows 8
* Windows
### Dziwactwa Androida
* Android obsługuje maksymalnie trzy przyciski i więcej niż to ignoruje.
* Android 3.0 i nowszych przyciski są wyświetlane w kolejności odwrotnej do urządzenia, które używają tematu Holo.
### Windows dziwactwa
* W systemie Windows wierzyciel okno jest oparte na języku html, ze względu na brak takich natywnego api.
### Firefox OS dziwactwa:
Dostępne są zarówno rodzimych blokuje `window.prompt()` i bez blokowania `navigator.notification.prompt()`.
## navigator.notification.beep
Urządzenie odtwarza sygnał ciągły dźwięk.
navigator.notification.beep(times);
* **times**: liczba powtórzeń po sygnale. *(Liczba)*
### Przykład
// Beep twice!
navigator.notification.beep(2);
### Obsługiwane platformy
* Amazon Fire OS
* Android
* BlackBerry 10
* iOS
* Tizen
* Windows Phone 7 i 8
* Windows 8
### Amazon ogień OS dziwactwa
* Amazon ogień OS gra domyślny **Dźwięk powiadomienia** określone w panelu **ekranu/ustawienia i dźwięk**.
### Dziwactwa Androida
* Android gra domyślnie **dzwonek powiadomienia** określone w panelu **ustawień/dźwięk i wyświetlacz**.
### Windows Phone 7 i 8 dziwactwa
* Opiera się na pliku rodzajowego sygnał z rozkładu Cordova.
### Dziwactwa Tizen
* Tizen implementuje dźwięków przez odtwarzania pliku audio za pośrednictwem mediów API.
* Plik dźwiękowy muszą być krótkie, musi znajdować się w podkatalogu `dźwięki` w katalogu głównym aplikacji i musi być o nazwie `beep.wav`.

View File

@@ -0,0 +1,247 @@
<!---
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# cordova-plugin-dialogs
Этот плагин обеспечивает доступ к некоторым элементам собственного диалогового окна пользовательского интерфейса.
## Установка
cordova plugin add cordova-plugin-dialogs
## Методы
* `navigator.notification.alert`
* `navigator.notification.confirm`
* `navigator.notification.prompt`
* `navigator.notification.beep`
## navigator.notification.alert
Показывает окно пользовательские оповещения или диалоговое окно. Большинство реализаций Cordova использовать диалоговое окно родной для этой функции, но некоторые платформы браузера `alert` функция, которая как правило менее настраивается.
Navigator.Notification.Alert (сообщение, alertCallback, [название], [buttonName])
* **сообщение**: сообщение диалога. *(Строка)*
* **alertCallback**: обратного вызова для вызова, когда закрывается диалоговое окно оповещения. *(Функция)*
* **название**: диалоговое окно название. *(Строка)* (Опционально, по умолчанию`Alert`)
* **buttonName**: имя кнопки. *(Строка)* (Опционально, по умолчанию`OK`)
### Пример
function alertDismissed() {
// do something
}
navigator.notification.alert(
'You are the winner!', // message
alertDismissed, // callback
'Game Over', // title
'Done' // buttonName
);
### Поддерживаемые платформы
* Amazon Fire OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 и 8
* Windows 8
### Особенности Windows Phone 7 и 8
* Существует предупреждение не встроенный браузер, но можно привязать один следующим позвонить `alert()` в глобальной области действия:
window.alert = navigator.notification.alert;
* Оба `alert` и `confirm` являются не блокировка звонков, результаты которых доступны только асинхронно.
### Firefox OS причуды:
Как родной блокировка `window.alert()` и неблокирующий `navigator.notification.alert()` доступны.
## navigator.notification.confirm
Отображает диалоговое окно Настраиваемый подтверждения.
navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels])
* **сообщение**: сообщение диалога. *(Строка)*
* **confirmCallback**: обратного вызова с индексом кнопка нажата (1, 2 или 3) или когда диалоговое окно закрывается без нажатия кнопки (0). *(Функция)*
* **название**: диалоговое окно название. *(Строка)* (Опционально, по умолчанию`Confirm`)
* **buttonLabels**: массив строк, указав названия кнопок. *(Массив)* (Не обязательно, по умолчанию [ `OK,Cancel` ])
### confirmCallback
`confirmCallback`Выполняется, когда пользователь нажимает одну из кнопок в диалоговом окне подтверждения.
Аргументом функции обратного вызова `buttonIndex` *(номер)*, который является индекс нажатой кнопки. Обратите внимание, что индекс использует единицы индексации, поэтому значение `1` , `2` , `3` , и т.д.
### Пример
function onConfirm(buttonIndex) {
alert('You selected button ' + buttonIndex);
}
navigator.notification.confirm(
'You are the winner!', // message
onConfirm, // callback to invoke with index of button pressed
'Game Over', // title
['Restart','Exit'] // buttonLabels
);
### Поддерживаемые платформы
* Amazon Fire OS
* Android
* BlackBerry 10
* Firefox OS
* iOS
* Tizen
* Windows Phone 7 и 8
* Windows 8
### Особенности Windows Phone 7 и 8
* Нет встроенного браузера функция для `window.confirm` , но его можно привязать путем присвоения:
window.confirm = navigator.notification.confirm;
* Вызовы `alert` и `confirm` являются не блокируется, поэтому результат доступен только асинхронно.
### Firefox OS причуды:
Как родной блокировка `window.confirm()` и неблокирующий `navigator.notification.confirm()` доступны.
## navigator.notification.prompt
Отображает родной диалоговое окно более настраиваемый, чем в браузере `prompt` функции.
navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText])
* **сообщение**: сообщение диалога. *(Строка)*
* **promptCallback**: обратного вызова с индексом кнопка нажата (1, 2 или 3) или когда диалоговое окно закрывается без нажатия кнопки (0). *(Функция)*
* **название**: диалоговое окно название *(String)* (опционально, по умолчанию`Prompt`)
* **buttonLabels**: массив строк, указав кнопку этикетки *(массив)* (опционально, по умолчанию`["OK","Cancel"]`)
* **defaultText**: по умолчанию textbox входное значение ( `String` ) (опционально, по умолчанию: пустая строка)
### promptCallback
`promptCallback`Выполняется, когда пользователь нажимает одну из кнопок в диалоговом окне приглашения. `results`Объект, переданный в метод обратного вызова содержит следующие свойства:
* **buttonIndex**: индекс нажатой кнопки. *(Число)* Обратите внимание, что индекс использует единицы индексации, поэтому значение `1` , `2` , `3` , и т.д.
* **INPUT1**: текст, введенный в диалоговом окне приглашения. *(Строка)*
### Пример
function onPrompt(results) {
alert("You selected button number " + results.buttonIndex + " and entered " + results.input1);
}
navigator.notification.prompt(
'Please enter your name', // message
onPrompt, // callback to invoke
'Registration', // title
['Ok','Exit'], // buttonLabels
'Jane Doe' // defaultText
);
### Поддерживаемые платформы
* Amazon Fire OS
* Android
* Firefox OS
* iOS
* Windows Phone 7 и 8
### Особенности Android
* Android поддерживает максимум из трех кнопок и игнорирует больше, чем это.
* На Android 3.0 и более поздних версиях кнопки отображаются в обратном порядке для устройств, которые используют тему холо.
### Firefox OS причуды:
Как родной блокировка `window.prompt()` и неблокирующий `navigator.notification.prompt()` доступны.
## navigator.notification.beep
Устройство воспроизводит звуковой сигнал звук.
navigator.notification.beep(times);
* **раз**: количество раз, чтобы повторить сигнал. *(Число)*
### Пример
// Beep twice!
navigator.notification.beep(2);
### Поддерживаемые платформы
* Amazon Fire OS
* Android
* BlackBerry 10
* iOS
* Tizen
* Windows Phone 7 и 8
* Windows 8
### Особенности Amazon Fire OS
* Amazon Fire OS играет по умолчанию **Звук уведомления** , указанного на панели **параметров/дисплей и звук** .
### Особенности Android
* Android играет по умолчанию **уведомления рингтон** указанных в панели **настройки/звук и дисплей** .
### Особенности Windows Phone 7 и 8
* Опирается на общий звуковой файл из дистрибутива Кордова.
### Особенности Tizen
* Tizen реализует гудков, воспроизведении аудиофайла через СМИ API.
* Звуковой файл должен быть коротким, должен быть расположен в `sounds` подкаталог корневого каталога приложения и должны быть названы`beep.wav`.

View File

@@ -0,0 +1,275 @@
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-->
# cordova-plugin-dialogs
[![Build Status](https://travis-ci.org/apache/cordova-plugin-dialogs.svg)](https://travis-ci.org/apache/cordova-plugin-dialogs)
這個外掛程式提供對一些本機對話方塊使用者介面元素,通過全球 `navigator.notification` 物件的訪問。
雖然該物件附加到全球範圍內 `導航器`,它不可用直到 `deviceready` 事件之後。
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.notification);
}
## 安裝
cordova plugin add cordova-plugin-dialogs
## 方法
* `navigator.notification.alert`
* `navigator.notification.confirm`
* `navigator.notification.prompt`
* `navigator.notification.beep`
## navigator.notification.alert
顯示一個自訂的警報或對話方塊框。 大多數的科爾多瓦實現使用本機的對話方塊為此功能,但某些平臺上使用瀏覽器的 `alert` 功能,這是通常不那麼可自訂。
navigator.notification.alert(message, alertCallback, [title], [buttonName])
* **message** 消息對話方塊。*String*
* **alertCallback** 當警報對話方塊的被解雇時要調用的回檔。*(函數)*
* **title** 標題對話方塊。*String*(可選,預設值為`Alert`)
* **buttonName** 按鈕名稱。*(字串)*(可選,預設值為`OK`)
### 示例
function alertDismissed() {
// do something
}
navigator.notification.alert(
'You are the winner!', // message
alertDismissed, // callback
'Game Over', // title
'Done' // buttonName
);
### 支援的平臺
* 亞馬遜火 OS
* Android 系統
* 黑莓 10
* 火狐瀏覽器作業系統
* iOS
* Tizen
* Windows Phone 7 和 8
* Windows 8
* Windows
### Windows Phone 7 和 8 怪癖
* 有沒有內置瀏覽器警報,但你可以綁定一個,如下所示調用 `alert()` 在全球範圍內:
window.alert = navigator.notification.alert;
* 兩個 `alert``confirm` 的非阻塞的調用,其中的結果才是可用的非同步。
### 火狐瀏覽器作業系統怪癖:
本機阻止 `window.alert()` 和非阻塞的 `navigator.notification.alert()` 都可。
### 黑莓 10 怪癖
`navigator.notification.alert ('message'、 confirmCallback、 'title'、 'buttonLabels')` 回檔參數被傳遞的數位 1。
## navigator.notification.confirm
顯示一個可自訂的確認對話方塊。
navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels])
* **message** 消息對話方塊。*String*
* **confirmCallback**: 要用索引 1、 2 或 3 按下的按鈕,或者在沒有按下按鈕 (0) 駁回了對話方塊中時調用的回檔。*(函數)*
* **title** 標題對話方塊。*(字串)*(可選,預設值為`Confirm`)
* **buttonLabels** 指定按鈕標籤的字串陣列。*(陣列)*(可選,預設值為 [ `OK,Cancel` ])
### confirmCallback
當使用者按下確認對話方塊中的按鈕之一時,將執行 `confirmCallback`
回檔需要參數 `buttonIndex` *(編號)*,即按下的按鈕的索引。 請注意索引使用一個基於索引,因此值 `1``2``3` 等。
### 示例
function onConfirm(buttonIndex) {
alert('You selected button ' + buttonIndex);
}
navigator.notification.confirm(
'You are the winner!', // message
onConfirm, // callback to invoke with index of button pressed
'Game Over', // title
['Restart','Exit'] // buttonLabels
);
### 支援的平臺
* 亞馬遜火 OS
* Android 系統
* 黑莓 10
* 火狐瀏覽器作業系統
* iOS
* Tizen
* Windows Phone 7 和 8
* Windows 8
* Windows
### Windows Phone 7 和 8 怪癖
* 有沒有內置的瀏覽器功能的 `window.confirm` ,但你可以將它綁定通過分配:
window.confirm = navigator.notification.confirm;
* 調用到 `alert``confirm` 的非阻塞,所以結果就是只可用以非同步方式。
### Windows 的怪癖
* 在 Windows8/8.1 它是不可能將超過三個按鈕添加到 MessageDialog 實例。
* 在 Windows Phone 8.1 它是不可能顯示有超過兩個按鈕的對話方塊。
### 火狐瀏覽器作業系統怪癖:
本機阻止 `window.confirm()` 和非阻塞的 `navigator.notification.confirm()` 都可。
## navigator.notification.prompt
顯示本機的對話方塊,是可定制的比瀏覽器的 `prompt` 功能。
navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText])
* **message** 消息對話方塊。*String*
* **promptCallback** 要用指數 1、 2 或 3 按下的按鈕或對話方塊中解雇無 (0) 按下一個按鈕時調用的回檔。*(函數)*
* **title** 標題對話方塊。*String*(可選,預設值為`Alert`)
* **buttonLabels** 指定按鈕標籤 (可選,預設值為 `["OK""Cancel"]` *(陣列)* 的字串陣列)
* **defaultText**: 預設文字方塊中輸入值 `字串` (可選,預設值: 空字串)
### promptCallback
當使用者按下其中一個提示對話方塊中的按鈕時,將執行 `promptCallback`。傳遞給回檔的 `results` 物件包含以下屬性:
* **buttonIndex** 按下的按鈕的索引。*(數)*請注意索引使用一個基於索引,因此值 `1``2``3` 等。
* **input1** 在提示對話方塊中輸入的文本。*(字串)*
### 示例
function onPrompt(results) {
alert("You selected button number " + results.buttonIndex + " and entered " + results.input1);
}
navigator.notification.prompt(
'Please enter your name', // message
onPrompt, // callback to invoke
'Registration', // title
['Ok','Exit'], // buttonLabels
'Jane Doe' // defaultText
);
### 支援的平臺
* 亞馬遜火 OS
* Android 系統
* 火狐瀏覽器作業系統
* iOS
* Windows Phone 7 和 8
* Windows 8
* Windows
### Android 的怪癖
* Android 支援最多的三個按鈕,並忽略任何更多。
* 在 Android 3.0 及更高版本,使用全息主題的設備以相反的順序顯示按鈕。
### Windows 的怪癖
* 在 Windows 上提示對話方塊是基於 html 的缺乏這種本機 api。
### 火狐瀏覽器作業系統怪癖:
本機阻止 `window.prompt()` 和非阻塞的 `navigator.notification.prompt()` 都可。
## navigator.notification.beep
該設備播放提示音的聲音。
navigator.notification.beep(times);
* **beep** 次數重複在嗶嗶聲。*(數)*
### 示例
// Beep twice!
navigator.notification.beep(2);
### 支援的平臺
* 亞馬遜火 OS
* Android 系統
* 黑莓 10
* iOS
* Tizen
* Windows Phone 7 和 8
* Windows 8
### 亞馬遜火 OS 怪癖
* 亞馬遜火 OS 播放預設 **設置/顯示和聲音** 板下指定的 **通知聲音**
### Android 的怪癖
* 安卓系統播放預設 **通知鈴聲** **設置/聲音和顯示** 面板下指定。
### Windows Phone 7 和 8 怪癖
* 依賴于泛型蜂鳴音檔從科爾多瓦分佈。
### Tizen 怪癖
* Tizen 通過播放音訊檔通過媒體 API 實現的蜂鳴聲。
* 蜂鳴音檔必須很短,必須位於應用程式的根目錄中,一個 `聲音` 子目錄和必須將命名為 `beep.wav`.

View File

@@ -0,0 +1,273 @@
<!---
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
# cordova-plugin-dialogs
這個外掛程式提供對一些本機對話方塊使用者介面元素,通過全球 `navigator.notification` 物件的訪問。
雖然該物件附加到全球範圍內 `導航器`,它不可用直到 `deviceready` 事件之後。
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
console.log(navigator.notification);
}
## 安裝
cordova plugin add cordova-plugin-dialogs
## 方法
* `navigator.notification.alert`
* `navigator.notification.confirm`
* `navigator.notification.prompt`
* `navigator.notification.beep`
## navigator.notification.alert
顯示一個自訂的警報或對話方塊框。 大多數的科爾多瓦實現使用本機的對話方塊為此功能,但某些平臺上使用瀏覽器的 `alert` 功能,這是通常不那麼可自訂。
navigator.notification.alert(message, alertCallback, [title], [buttonName])
* **message** 消息對話方塊。*String*
* **alertCallback** 當警報對話方塊的被解雇時要調用的回檔。*(函數)*
* **title** 標題對話方塊。*String*(可選,預設值為`Alert`)
* **buttonName** 按鈕名稱。*(字串)*(可選,預設值為`OK`)
### 示例
function alertDismissed() {
// do something
}
navigator.notification.alert(
'You are the winner!', // message
alertDismissed, // callback
'Game Over', // title
'Done' // buttonName
);
### 支援的平臺
* 亞馬遜火 OS
* Android 系統
* 黑莓 10
* 火狐瀏覽器作業系統
* iOS
* Tizen
* Windows Phone 7 和 8
* Windows 8
* Windows
### Windows Phone 7 和 8 怪癖
* 有沒有內置瀏覽器警報,但你可以綁定一個,如下所示調用 `alert()` 在全球範圍內:
window.alert = navigator.notification.alert;
* 兩個 `alert``confirm` 的非阻塞的調用,其中的結果才是可用的非同步。
### 火狐瀏覽器作業系統怪癖:
本機阻止 `window.alert()` 和非阻塞的 `navigator.notification.alert()` 都可。
### 黑莓 10 怪癖
`navigator.notification.alert ('message'、 confirmCallback、 'title'、 'buttonLabels')` 回檔參數被傳遞的數位 1。
## navigator.notification.confirm
顯示一個可自訂的確認對話方塊。
navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels])
* **message** 消息對話方塊。*(字串)*
* **confirmCallback**: 要用索引 1、 2 或 3 按下的按鈕,或者在沒有按下按鈕 (0) 駁回了對話方塊中時調用的回檔。*(函數)*
* **title** 標題對話方塊。*(字串)*(可選,預設值為`Confirm`)
* **buttonLabels** 指定按鈕標籤的字串陣列。*(陣列)*(可選,預設值為 [ `OK,Cancel` ])
### confirmCallback
當使用者按下確認對話方塊中的按鈕之一時,將執行 `confirmCallback`
回檔需要參數 `buttonIndex` *(編號)*,即按下的按鈕的索引。 請注意索引使用一個基於索引,因此值 `1``2``3` 等。
### 示例
function onConfirm(buttonIndex) {
alert('You selected button ' + buttonIndex);
}
navigator.notification.confirm(
'You are the winner!', // message
onConfirm, // callback to invoke with index of button pressed
'Game Over', // title
['Restart','Exit'] // buttonLabels
);
### 支援的平臺
* 亞馬遜火 OS
* Android 系統
* 黑莓 10
* 火狐瀏覽器作業系統
* iOS
* Tizen
* Windows Phone 7 和 8
* Windows 8
* Windows
### Windows Phone 7 和 8 怪癖
* 有沒有內置的瀏覽器功能的 `window.confirm` ,但你可以將它綁定通過分配:
window.confirm = navigator.notification.confirm;
* 調用到 `alert``confirm` 的非阻塞,所以結果就是只可用以非同步方式。
### Windows 的怪癖
* 在 Windows8/8.1 它是不可能將超過三個按鈕添加到 MessageDialog 實例。
* 在 Windows Phone 8.1 它是不可能顯示有超過兩個按鈕的對話方塊。
### 火狐瀏覽器作業系統怪癖:
本機阻止 `window.confirm()` 和非阻塞的 `navigator.notification.confirm()` 都可。
## navigator.notification.prompt
顯示本機的對話方塊,是可定制的比瀏覽器的 `prompt` 功能。
navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText])
* **message** 消息對話方塊。*String*
* **promptCallback** 要用指數 1、 2 或 3 按下的按鈕或對話方塊中解雇無 (0) 按下一個按鈕時調用的回檔。*(函數)*
* **title** 標題對話方塊。*String*(可選,預設值為`Alert`)
* **buttonLabels** 指定按鈕標籤 (可選,預設值為 `["OK""Cancel"]` *(陣列)* 的字串陣列)
* **defaultText**: 預設文字方塊中輸入值 `字串` (可選,預設值: 空字串)
### promptCallback
當使用者按下其中一個提示對話方塊中的按鈕時,將執行 `promptCallback`。傳遞給回檔的 `results` 物件包含以下屬性:
* **buttonIndex** 按下的按鈕的索引。*(數)*請注意索引使用一個基於索引,因此值 `1``2``3` 等。
* **input1** 在提示對話方塊中輸入的文本。*(字串)*
### 示例
function onPrompt(results) {
alert("You selected button number " + results.buttonIndex + " and entered " + results.input1);
}
navigator.notification.prompt(
'Please enter your name', // message
onPrompt, // callback to invoke
'Registration', // title
['Ok','Exit'], // buttonLabels
'Jane Doe' // defaultText
);
### 支援的平臺
* 亞馬遜火 OS
* Android 系統
* 火狐瀏覽器作業系統
* iOS
* Windows Phone 7 和 8
* Windows 8
* Windows
### Android 的怪癖
* Android 支援最多的三個按鈕,並忽略任何更多。
* 在 Android 3.0 及更高版本,使用全息主題的設備以相反的順序顯示按鈕。
### Windows 的怪癖
* 在 Windows 上提示對話方塊是基於 html 的缺乏這種本機 api。
### 火狐瀏覽器作業系統怪癖:
本機阻止 `window.prompt()` 和非阻塞的 `navigator.notification.prompt()` 都可。
## navigator.notification.beep
該設備播放提示音的聲音。
navigator.notification.beep(times);
* **beep** 次數重複在嗶嗶聲。*(數)*
### 示例
// Beep twice!
navigator.notification.beep(2);
### 支援的平臺
* 亞馬遜火 OS
* Android 系統
* 黑莓 10
* iOS
* Tizen
* Windows Phone 7 和 8
* Windows 8
### 亞馬遜火 OS 怪癖
* 亞馬遜火 OS 播放預設 **設置/顯示和聲音** 板下指定的 **通知聲音**
### Android 的怪癖
* 安卓系統播放預設 **通知鈴聲** **設置/聲音和顯示** 面板下指定。
### Windows Phone 7 和 8 怪癖
* 依賴于泛型蜂鳴音檔從科爾多瓦分佈。
### Tizen 怪癖
* Tizen 通過播放音訊檔通過媒體 API 實現的蜂鳴聲。
* 蜂鳴音檔必須很短,必須位於應用程式的根目錄中,一個 `聲音` 子目錄和必須將命名為 `beep.wav`.

View File

@@ -0,0 +1,82 @@
{
"_from": "cordova-plugin-dialogs",
"_id": "cordova-plugin-dialogs@2.0.1",
"_inBundle": false,
"_integrity": "sha1-N/7xUSWWyNXflUP7eHJFkPdn3PM=",
"_location": "/cordova-plugin-dialogs",
"_phantomChildren": {},
"_requested": {
"type": "tag",
"registry": true,
"raw": "cordova-plugin-dialogs",
"name": "cordova-plugin-dialogs",
"escapedName": "cordova-plugin-dialogs",
"rawSpec": "",
"saveSpec": null,
"fetchSpec": "latest"
},
"_requiredBy": [
"#USER",
"/"
],
"_resolved": "https://registry.npmjs.org/cordova-plugin-dialogs/-/cordova-plugin-dialogs-2.0.1.tgz",
"_shasum": "37fef1512596c8d5df9543fb78724590f767dcf3",
"_spec": "cordova-plugin-dialogs",
"_where": "/Users/nicco/Documents/git/fight-of-the-mobiles/src/cordova",
"author": {
"name": "Apache Software Foundation"
},
"bugs": {
"url": "https://issues.apache.org/jira/browse/CB"
},
"bundleDependencies": false,
"cordova": {
"id": "cordova-plugin-dialogs",
"platforms": [
"android",
"browser",
"ios",
"windows"
]
},
"deprecated": false,
"description": "Cordova Notification Plugin",
"devDependencies": {
"eslint": "^3.19.0",
"eslint-config-semistandard": "^11.0.0",
"eslint-config-standard": "^10.2.1",
"eslint-plugin-import": "^2.3.0",
"eslint-plugin-node": "^5.0.0",
"eslint-plugin-promise": "^3.5.0",
"eslint-plugin-standard": "^3.0.1"
},
"engines": {
"cordovaDependencies": {
"3.0.0": {
"cordova": ">100"
}
}
},
"homepage": "https://github.com/apache/cordova-plugin-dialogs#readme",
"keywords": [
"cordova",
"notification",
"ecosystem:cordova",
"cordova-android",
"cordova-browser",
"cordova-ios",
"cordova-windows"
],
"license": "Apache-2.0",
"name": "cordova-plugin-dialogs",
"repository": {
"type": "git",
"url": "git+https://github.com/apache/cordova-plugin-dialogs.git"
},
"scripts": {
"eslint": "node node_modules/eslint/bin/eslint www && node node_modules/eslint/bin/eslint src && node node_modules/eslint/bin/eslint tests",
"test": "npm run eslint"
},
"types": "./types/index.d.ts",
"version": "2.0.1"
}

View File

@@ -0,0 +1,82 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
id="cordova-plugin-dialogs"
version="2.0.1">
<name>Notification</name>
<description>Cordova Notification Plugin</description>
<license>Apache 2.0</license>
<keywords>cordova,notification</keywords>
<repo>https://git-wip-us.apache.org/repos/asf/cordova-plugin-dialogs.git</repo>
<issue>https://issues.apache.org/jira/browse/CB/component/12320642</issue>
<js-module src="www/notification.js" name="notification">
<merges target="navigator.notification" />
</js-module>
<!-- android -->
<platform name="android">
<config-file target="res/xml/config.xml" parent="/*">
<feature name="Notification">
<param name="android-package" value="org.apache.cordova.dialogs.Notification"/>
</feature>
</config-file>
<source-file src="src/android/Notification.java" target-dir="src/org/apache/cordova/dialogs" />
<!-- android specific notification apis -->
<js-module src="www/android/notification.js" name="notification_android">
<merges target="navigator.notification" />
</js-module>
</platform>
<!-- browser -->
<platform name="browser">
<js-module src="www/browser/notification.js" name="notification_browser">
<merges target="navigator.notification" />
</js-module>
</platform>
<!-- ios -->
<platform name="ios">
<config-file target="config.xml" parent="/*">
<feature name="Notification">
<param name="ios-package" value="CDVNotification"/>
</feature>
</config-file>
<header-file src="src/ios/CDVNotification.h" />
<source-file src="src/ios/CDVNotification.m" />
<resource-file src="src/ios/CDVNotification.bundle" />
<framework src="AudioToolbox.framework" weak="true" />
</platform>
<!-- windows -->
<platform name="windows">
<js-module src="src/windows/NotificationProxy.js" name="NotificationProxy">
<runs />
</js-module>
<asset src="www/windows/notification.css" target="css/notification.css" />
</platform>
</plugin>

View File

@@ -0,0 +1,513 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
package org.apache.cordova.dialogs;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaInterface;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.LOG;
import org.apache.cordova.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.widget.EditText;
import android.widget.TextView;
/**
* This class provides access to notifications on the device.
*
* Be aware that this implementation gets called on
* navigator.notification.{alert|confirm|prompt}, and that there is a separate
* implementation in org.apache.cordova.CordovaChromeClient that gets
* called on a simple window.{alert|confirm|prompt}.
*/
public class Notification extends CordovaPlugin {
private static final String LOG_TAG = "Notification";
public int confirmResult = -1;
public ProgressDialog spinnerDialog = null;
public ProgressDialog progressDialog = null;
/**
* Constructor.
*/
public Notification() {
}
/**
* Executes the request and returns PluginResult.
*
* @param action The action to execute.
* @param args JSONArray of arguments for the plugin.
* @param callbackContext The callback context used when calling back into JavaScript.
* @return True when the action was valid, false otherwise.
*/
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
/*
* Don't run any of these if the current activity is finishing
* in order to avoid android.view.WindowManager$BadTokenException
* crashing the app. Just return true here since false should only
* be returned in the event of an invalid action.
*/
if(this.cordova.getActivity().isFinishing()) return true;
if (action.equals("beep")) {
this.beep(args.getLong(0));
}
else if (action.equals("alert")) {
this.alert(args.getString(0), args.getString(1), args.getString(2), callbackContext);
return true;
}
else if (action.equals("confirm")) {
this.confirm(args.getString(0), args.getString(1), args.getJSONArray(2), callbackContext);
return true;
}
else if (action.equals("prompt")) {
this.prompt(args.getString(0), args.getString(1), args.getJSONArray(2), args.getString(3), callbackContext);
return true;
}
else if (action.equals("activityStart")) {
this.activityStart(args.getString(0), args.getString(1));
}
else if (action.equals("activityStop")) {
this.activityStop();
}
else if (action.equals("progressStart")) {
this.progressStart(args.getString(0), args.getString(1));
}
else if (action.equals("progressValue")) {
this.progressValue(args.getInt(0));
}
else if (action.equals("progressStop")) {
this.progressStop();
}
else {
return false;
}
// Only alert and confirm are async.
callbackContext.success();
return true;
}
//--------------------------------------------------------------------------
// LOCAL METHODS
//--------------------------------------------------------------------------
/**
* Beep plays the default notification ringtone.
*
* @param count Number of times to play notification
*/
public void beep(final long count) {
cordova.getThreadPool().execute(new Runnable() {
public void run() {
Uri ringtone = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone notification = RingtoneManager.getRingtone(cordova.getActivity().getBaseContext(), ringtone);
// If phone is not set to silent mode
if (notification != null) {
for (long i = 0; i < count; ++i) {
notification.play();
long timeout = 5000;
while (notification.isPlaying() && (timeout > 0)) {
timeout = timeout - 100;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
}
});
}
/**
* Builds and shows a native Android alert with given Strings
* @param message The message the alert should display
* @param title The title of the alert
* @param buttonLabel The label of the button
* @param callbackContext The callback context
*/
public synchronized void alert(final String message, final String title, final String buttonLabel, final CallbackContext callbackContext) {
final CordovaInterface cordova = this.cordova;
Runnable runnable = new Runnable() {
public void run() {
AlertDialog.Builder dlg = createDialog(cordova); // new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
dlg.setMessage(message);
dlg.setTitle(title);
dlg.setCancelable(true);
dlg.setPositiveButton(buttonLabel,
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0));
}
});
dlg.setOnCancelListener(new AlertDialog.OnCancelListener() {
public void onCancel(DialogInterface dialog)
{
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0));
}
});
changeTextDirection(dlg);
};
};
this.cordova.getActivity().runOnUiThread(runnable);
}
/**
* Builds and shows a native Android confirm dialog with given title, message, buttons.
* This dialog only shows up to 3 buttons. Any labels after that will be ignored.
* The index of the button pressed will be returned to the JavaScript callback identified by callbackId.
*
* @param message The message the dialog should display
* @param title The title of the dialog
* @param buttonLabels A comma separated list of button labels (Up to 3 buttons)
* @param callbackContext The callback context.
*/
public synchronized void confirm(final String message, final String title, final JSONArray buttonLabels, final CallbackContext callbackContext) {
final CordovaInterface cordova = this.cordova;
Runnable runnable = new Runnable() {
public void run() {
AlertDialog.Builder dlg = createDialog(cordova); // new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
dlg.setMessage(message);
dlg.setTitle(title);
dlg.setCancelable(true);
// First button
if (buttonLabels.length() > 0) {
try {
dlg.setNegativeButton(buttonLabels.getString(0),
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 1));
}
});
} catch (JSONException e) {
LOG.d(LOG_TAG,"JSONException on first button.");
}
}
// Second button
if (buttonLabels.length() > 1) {
try {
dlg.setNeutralButton(buttonLabels.getString(1),
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 2));
}
});
} catch (JSONException e) {
LOG.d(LOG_TAG,"JSONException on second button.");
}
}
// Third button
if (buttonLabels.length() > 2) {
try {
dlg.setPositiveButton(buttonLabels.getString(2),
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 3));
}
});
} catch (JSONException e) {
LOG.d(LOG_TAG,"JSONException on third button.");
}
}
dlg.setOnCancelListener(new AlertDialog.OnCancelListener() {
public void onCancel(DialogInterface dialog)
{
dialog.dismiss();
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, 0));
}
});
changeTextDirection(dlg);
};
};
this.cordova.getActivity().runOnUiThread(runnable);
}
/**
* Builds and shows a native Android prompt dialog with given title, message, buttons.
* This dialog only shows up to 3 buttons. Any labels after that will be ignored.
* The following results are returned to the JavaScript callback identified by callbackId:
* buttonIndex Index number of the button selected
* input1 The text entered in the prompt dialog box
*
* @param message The message the dialog should display
* @param title The title of the dialog
* @param buttonLabels A comma separated list of button labels (Up to 3 buttons)
* @param callbackContext The callback context.
*/
public synchronized void prompt(final String message, final String title, final JSONArray buttonLabels, final String defaultText, final CallbackContext callbackContext) {
final CordovaInterface cordova = this.cordova;
Runnable runnable = new Runnable() {
public void run() {
final EditText promptInput = new EditText(cordova.getActivity());
/* CB-11677 - By default, prompt input text color is set according current theme.
But for some android versions is not visible (for example 5.1.1).
android.R.color.primary_text_light will make text visible on all versions. */
Resources resources = cordova.getActivity().getResources();
int promptInputTextColor = resources.getColor(android.R.color.primary_text_light);
promptInput.setTextColor(promptInputTextColor);
promptInput.setText(defaultText);
AlertDialog.Builder dlg = createDialog(cordova); // new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
dlg.setMessage(message);
dlg.setTitle(title);
dlg.setCancelable(true);
dlg.setView(promptInput);
final JSONObject result = new JSONObject();
// First button
if (buttonLabels.length() > 0) {
try {
dlg.setNegativeButton(buttonLabels.getString(0),
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
try {
result.put("buttonIndex",1);
result.put("input1", promptInput.getText().toString().trim().length()==0 ? defaultText : promptInput.getText());
} catch (JSONException e) {
LOG.d(LOG_TAG,"JSONException on first button.", e);
}
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
}
});
} catch (JSONException e) {
LOG.d(LOG_TAG,"JSONException on first button.");
}
}
// Second button
if (buttonLabels.length() > 1) {
try {
dlg.setNeutralButton(buttonLabels.getString(1),
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
try {
result.put("buttonIndex",2);
result.put("input1", promptInput.getText().toString().trim().length()==0 ? defaultText : promptInput.getText());
} catch (JSONException e) {
LOG.d(LOG_TAG,"JSONException on second button.", e);
}
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
}
});
} catch (JSONException e) {
LOG.d(LOG_TAG,"JSONException on second button.");
}
}
// Third button
if (buttonLabels.length() > 2) {
try {
dlg.setPositiveButton(buttonLabels.getString(2),
new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
try {
result.put("buttonIndex",3);
result.put("input1", promptInput.getText().toString().trim().length()==0 ? defaultText : promptInput.getText());
} catch (JSONException e) {
LOG.d(LOG_TAG,"JSONException on third button.", e);
}
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
}
});
} catch (JSONException e) {
LOG.d(LOG_TAG,"JSONException on third button.");
}
}
dlg.setOnCancelListener(new AlertDialog.OnCancelListener() {
public void onCancel(DialogInterface dialog){
dialog.dismiss();
try {
result.put("buttonIndex",0);
result.put("input1", promptInput.getText().toString().trim().length()==0 ? defaultText : promptInput.getText());
} catch (JSONException e) { e.printStackTrace(); }
callbackContext.sendPluginResult(new PluginResult(PluginResult.Status.OK, result));
}
});
changeTextDirection(dlg);
};
};
this.cordova.getActivity().runOnUiThread(runnable);
}
/**
* Show the spinner.
*
* @param title Title of the dialog
* @param message The message of the dialog
*/
public synchronized void activityStart(final String title, final String message) {
if (this.spinnerDialog != null) {
this.spinnerDialog.dismiss();
this.spinnerDialog = null;
}
final Notification notification = this;
final CordovaInterface cordova = this.cordova;
Runnable runnable = new Runnable() {
public void run() {
notification.spinnerDialog = createProgressDialog(cordova); // new ProgressDialog(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
notification.spinnerDialog.setTitle(title);
notification.spinnerDialog.setMessage(message);
notification.spinnerDialog.setCancelable(true);
notification.spinnerDialog.setIndeterminate(true);
notification.spinnerDialog.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
notification.spinnerDialog = null;
}
});
notification.spinnerDialog.show();
}
};
this.cordova.getActivity().runOnUiThread(runnable);
}
/**
* Stop spinner.
*/
public synchronized void activityStop() {
if (this.spinnerDialog != null) {
this.spinnerDialog.dismiss();
this.spinnerDialog = null;
}
}
/**
* Show the progress dialog.
*
* @param title Title of the dialog
* @param message The message of the dialog
*/
public synchronized void progressStart(final String title, final String message) {
if (this.progressDialog != null) {
this.progressDialog.dismiss();
this.progressDialog = null;
}
final Notification notification = this;
final CordovaInterface cordova = this.cordova;
Runnable runnable = new Runnable() {
public void run() {
notification.progressDialog = createProgressDialog(cordova); // new ProgressDialog(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
notification.progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
notification.progressDialog.setTitle(title);
notification.progressDialog.setMessage(message);
notification.progressDialog.setCancelable(true);
notification.progressDialog.setMax(100);
notification.progressDialog.setProgress(0);
notification.progressDialog.setOnCancelListener(
new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
notification.progressDialog = null;
}
});
notification.progressDialog.show();
}
};
this.cordova.getActivity().runOnUiThread(runnable);
}
/**
* Set value of progress bar.
*
* @param value 0-100
*/
public synchronized void progressValue(int value) {
if (this.progressDialog != null) {
this.progressDialog.setProgress(value);
}
}
/**
* Stop progress dialog.
*/
public synchronized void progressStop() {
if (this.progressDialog != null) {
this.progressDialog.dismiss();
this.progressDialog = null;
}
}
@SuppressLint("NewApi")
private AlertDialog.Builder createDialog(CordovaInterface cordova) {
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.HONEYCOMB) {
return new AlertDialog.Builder(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
} else {
return new AlertDialog.Builder(cordova.getActivity());
}
}
@SuppressLint("InlinedApi")
private ProgressDialog createProgressDialog(CordovaInterface cordova) {
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
if (currentapiVersion >= android.os.Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
return new ProgressDialog(cordova.getActivity(), AlertDialog.THEME_DEVICE_DEFAULT_LIGHT);
} else {
return new ProgressDialog(cordova.getActivity());
}
}
@SuppressLint("NewApi")
private void changeTextDirection(Builder dlg){
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
dlg.create();
AlertDialog dialog = dlg.show();
if (currentapiVersion >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
TextView messageview = (TextView)dialog.findViewById(android.R.id.message);
messageview.setTextDirection(android.view.View.TEXT_DIRECTION_LOCALE);
}
}
}

View File

@@ -0,0 +1,37 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <AudioToolbox/AudioServices.h>
#import <Cordova/CDVPlugin.h>
@interface CDVNotification : CDVPlugin <UIAlertViewDelegate>{}
- (void)alert:(CDVInvokedUrlCommand*)command;
- (void)confirm:(CDVInvokedUrlCommand*)command;
- (void)prompt:(CDVInvokedUrlCommand*)command;
- (void)beep:(CDVInvokedUrlCommand*)command;
@end
@interface CDVAlertView : UIAlertView {}
@property (nonatomic, copy) NSString* callbackId;
@end

View File

@@ -0,0 +1,259 @@
/*
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
#import "CDVNotification.h"
#define DIALOG_TYPE_ALERT @"alert"
#define DIALOG_TYPE_PROMPT @"prompt"
static void soundCompletionCallback(SystemSoundID ssid, void* data);
static NSMutableArray *alertList = nil;
@implementation CDVNotification
/*
* showDialogWithMessage - Common method to instantiate the alert view for alert, confirm, and prompt notifications.
* Parameters:
* message The alert view message.
* title The alert view title.
* buttons The array of customized strings for the buttons.
* defaultText The input text for the textbox (if textbox exists).
* callbackId The commmand callback id.
* dialogType The type of alert view [alert | prompt].
*/
- (void)showDialogWithMessage:(NSString*)message title:(NSString*)title buttons:(NSArray*)buttons defaultText:(NSString*)defaultText callbackId:(NSString*)callbackId dialogType:(NSString*)dialogType
{
int count = (int)[buttons count];
#ifdef __IPHONE_8_0
if (NSClassFromString(@"UIAlertController")) {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
if ([[[UIDevice currentDevice] systemVersion] floatValue] < 8.3) {
CGRect alertFrame = [UIScreen mainScreen].applicationFrame;
if (UIInterfaceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation])) {
// swap the values for the app frame since it is now in landscape
CGFloat temp = alertFrame.size.width;
alertFrame.size.width = alertFrame.size.height;
alertFrame.size.height = temp;
}
alertController.view.frame = alertFrame;
}
__weak CDVNotification* weakNotif = self;
for (int n = 0; n < count; n++) {
[alertController addAction:[UIAlertAction actionWithTitle:[buttons objectAtIndex:n]
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
CDVPluginResult* result;
if ([dialogType isEqualToString:DIALOG_TYPE_PROMPT])
{
NSString* value0 = [[alertController.textFields objectAtIndex:0] text];
NSDictionary* info = @{
@"buttonIndex":@(n + 1),
@"input1":(value0 ? value0 : [NSNull null])
};
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:info];
}
else
{
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:(int)(n + 1)];
}
[weakNotif.commandDelegate sendPluginResult:result callbackId:callbackId];
}]];
}
if ([dialogType isEqualToString:DIALOG_TYPE_PROMPT]) {
[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.text = defaultText;
}];
}
if(!alertList)
alertList = [[NSMutableArray alloc] init];
[alertList addObject:alertController];
if ([alertList count]==1) {
[self presentAlertcontroller];
}
}
else
{
#endif
CDVAlertView* alertView = [[CDVAlertView alloc]
initWithTitle:title
message:message
delegate:self
cancelButtonTitle:nil
otherButtonTitles:nil];
alertView.callbackId = callbackId;
for (int n = 0; n < count; n++) {
[alertView addButtonWithTitle:[buttons objectAtIndex:n]];
}
if ([dialogType isEqualToString:DIALOG_TYPE_PROMPT]) {
alertView.alertViewStyle = UIAlertViewStylePlainTextInput;
UITextField* textField = [alertView textFieldAtIndex:0];
textField.text = defaultText;
}
[alertView show];
#ifdef __IPHONE_8_0
}
#endif
}
- (void)alert:(CDVInvokedUrlCommand*)command
{
NSString* callbackId = command.callbackId;
NSString* message = [command argumentAtIndex:0];
NSString* title = [command argumentAtIndex:1];
NSString* buttons = [command argumentAtIndex:2];
[self showDialogWithMessage:message title:title buttons:@[buttons] defaultText:nil callbackId:callbackId dialogType:DIALOG_TYPE_ALERT];
}
- (void)confirm:(CDVInvokedUrlCommand*)command
{
NSString* callbackId = command.callbackId;
NSString* message = [command argumentAtIndex:0];
NSString* title = [command argumentAtIndex:1];
NSArray* buttons = [command argumentAtIndex:2];
[self showDialogWithMessage:message title:title buttons:buttons defaultText:nil callbackId:callbackId dialogType:DIALOG_TYPE_ALERT];
}
- (void)prompt:(CDVInvokedUrlCommand*)command
{
NSString* callbackId = command.callbackId;
NSString* message = [command argumentAtIndex:0];
NSString* title = [command argumentAtIndex:1];
NSArray* buttons = [command argumentAtIndex:2];
NSString* defaultText = [command argumentAtIndex:3];
[self showDialogWithMessage:message title:title buttons:buttons defaultText:defaultText callbackId:callbackId dialogType:DIALOG_TYPE_PROMPT];
}
/**
* Callback invoked when an alert dialog's buttons are clicked.
*/
- (void)alertView:(UIAlertView*)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
CDVAlertView* cdvAlertView = (CDVAlertView*)alertView;
CDVPluginResult* result;
// Determine what gets returned to JS based on the alert view type.
if (alertView.alertViewStyle == UIAlertViewStyleDefault) {
// For alert and confirm, return button index as int back to JS.
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsInt:(int)(buttonIndex + 1)];
} else {
// For prompt, return button index and input text back to JS.
NSString* value0 = [[alertView textFieldAtIndex:0] text];
NSDictionary* info = @{
@"buttonIndex":@(buttonIndex + 1),
@"input1":(value0 ? value0 : [NSNull null])
};
result = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:info];
}
[self.commandDelegate sendPluginResult:result callbackId:cdvAlertView.callbackId];
}
- (void)didPresentAlertView:(UIAlertView*)alertView
{
//show keyboard on iOS 8
if (alertView.alertViewStyle == UIAlertViewStylePlainTextInput){
[[alertView textFieldAtIndex:0] selectAll:nil];
}
}
static void playBeep(int count) {
SystemSoundID completeSound;
NSInteger cbDataCount = count;
NSURL* audioPath = [[NSBundle mainBundle] URLForResource:@"CDVNotification.bundle/beep" withExtension:@"wav"];
#if __has_feature(objc_arc)
AudioServicesCreateSystemSoundID((__bridge CFURLRef)audioPath, &completeSound);
#else
AudioServicesCreateSystemSoundID((CFURLRef)audioPath, &completeSound);
#endif
AudioServicesAddSystemSoundCompletion(completeSound, NULL, NULL, soundCompletionCallback, (void*)(cbDataCount-1));
AudioServicesPlaySystemSound(completeSound);
}
static void soundCompletionCallback(SystemSoundID ssid, void* data) {
int count = (int)data;
AudioServicesRemoveSystemSoundCompletion (ssid);
AudioServicesDisposeSystemSoundID(ssid);
if (count > 0) {
playBeep(count);
}
}
- (void)beep:(CDVInvokedUrlCommand*)command
{
NSNumber* count = [command argumentAtIndex:0 withDefault:[NSNumber numberWithInt:1]];
playBeep([count intValue]);
}
-(UIViewController *)getTopPresentedViewController {
UIViewController *presentingViewController = self.viewController;
if (presentingViewController.view.window != [UIApplication sharedApplication].keyWindow){
presentingViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
}
while (presentingViewController.presentedViewController != nil && ![presentingViewController.presentedViewController isBeingDismissed]){
presentingViewController = presentingViewController.presentedViewController;
}
return presentingViewController;
}
-(void)presentAlertcontroller {
__weak CDVNotification* weakNotif = self;
[self.getTopPresentedViewController presentViewController:[alertList firstObject] animated:YES completion:^{
[alertList removeObject:[alertList firstObject]];
if ([alertList count]>0) {
[weakNotif presentAlertcontroller];
}
}];
}
@end
@implementation CDVAlertView
@synthesize callbackId;
@end

View File

@@ -0,0 +1,269 @@
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
/* global Windows:true, WinJS, toStaticHTML */
var cordova = require('cordova');
var urlutil = require('cordova/urlutil');
var isAlertShowing = false;
var alertStack = [];
function createCSSElem (fileName) {
var elemId = fileName.substr(0, fileName.lastIndexOf('.')) + '-plugin-style';
// If the CSS element exists, don't recreate it.
if (document.getElementById(elemId)) {
return false;
}
// Create CSS and append it to DOM.
var $elem = document.createElement('link');
$elem.id = elemId;
$elem.rel = 'stylesheet';
$elem.type = 'text/css';
$elem.href = urlutil.makeAbsolute('/www/css/' + fileName);
document.head.appendChild($elem);
return true;
}
// CB-8928: When toStaticHTML is undefined, prompt fails to run
var _cleanHtml = function (html) { return html; };
if (typeof toStaticHTML !== 'undefined') {
_cleanHtml = toStaticHTML;
}
// Windows does not provide native UI for promp dialog so we use some
// simple html-based implementation until it is available
function createPromptDialog (title, message, buttons, defaultText, callback) {
var isPhone = cordova.platformId === 'windows' && WinJS.Utilities.isPhone;
var isWindows = !!cordova.platformId.match(/windows/);
createCSSElem('notification.css');
var dlgWrap = document.createElement('div');
dlgWrap.className = 'dlgWrap';
var dlg = document.createElement('div');
dlg.className = 'dlgContainer';
if (isWindows) {
dlg.className += ' dlgContainer-windows';
} else if (isPhone) {
dlg.className += ' dlgContainer-phone';
}
// dialog layout template
dlg.innerHTML = _cleanHtml("<span id='lbl-title'></span><br/>" + // title
"<span id='lbl-message'></span><br/>" + // message
"<input id='prompt-input'/><br/>"); // input fields
dlg.querySelector('#lbl-title').appendChild(document.createTextNode(title));
dlg.querySelector('#lbl-message').appendChild(document.createTextNode(message));
dlg.querySelector('#prompt-input').setAttribute('placeholder', defaultText);
dlg.querySelector('#prompt-input').setAttribute('value', defaultText);
function makeButtonCallback (idx) {
return function () {
var value = dlg.querySelector('#prompt-input').value || defaultText;
dlgWrap.parentNode.removeChild(dlgWrap);
if (callback) {
callback({ input1: value, buttonIndex: idx }); // eslint-disable-line standard/no-callback-literal
}
};
}
function addButton (idx, label) {
var button = document.createElement('button');
button.className = 'dlgButton';
button.tabIndex = idx;
button.onclick = makeButtonCallback(idx + 1);
if (idx === 0) {
button.className += ' dlgButtonFirst';
}
button.appendChild(document.createTextNode(label));
dlg.appendChild(button);
}
// reverse order is used since we align buttons to the right
for (var idx = buttons.length - 1; idx >= 0; idx--) {
addButton(idx, buttons[idx]);
}
dlgWrap.appendChild(dlg);
document.body.appendChild(dlgWrap);
// make sure input field is under focus
dlg.querySelector('#prompt-input').select();
// add Enter/Return key handling
var defaultButton = dlg.querySelector('.dlgButtonFirst');
dlg.addEventListener('keypress', function (e) {
if (e.keyCode === 13) { // enter key
if (defaultButton) {
defaultButton.click();
}
}
});
return dlgWrap;
}
module.exports = {
alert: function (win, loseX, args) {
if (isAlertShowing) {
var later = function () {
module.exports.alert(win, loseX, args);
};
alertStack.push(later);
return;
}
isAlertShowing = true;
var message = args[0];
var _title = args[1];
var _buttonLabel = args[2];
var md = new Windows.UI.Popups.MessageDialog(message, _title);
md.commands.append(new Windows.UI.Popups.UICommand(_buttonLabel));
md.showAsync().then(function () {
isAlertShowing = false;
if (win) {
win();
}
if (alertStack.length) {
setTimeout(alertStack.shift(), 0);
}
});
},
prompt: function (win, lose, args) {
if (isAlertShowing) {
var later = function () {
module.exports.prompt(win, lose, args);
};
alertStack.push(later);
return;
}
isAlertShowing = true;
var message = args[0];
var title = args[1];
var buttons = args[2];
var defaultText = args[3];
try {
createPromptDialog(title, message, buttons, defaultText, function (evt) {
isAlertShowing = false;
if (win) {
win(evt);
}
});
} catch (e) {
// set isAlertShowing flag back to false in case of exception
isAlertShowing = false;
if (alertStack.length) {
setTimeout(alertStack.shift(), 0);
}
// rethrow exception
throw e;
}
},
confirm: function (win, loseX, args) {
if (isAlertShowing) {
var later = function () {
module.exports.confirm(win, loseX, args);
};
alertStack.push(later);
return;
}
isAlertShowing = true;
try {
var message = args[0];
var _title = args[1];
var buttons = args[2];
var md = new Windows.UI.Popups.MessageDialog(message, _title);
buttons.forEach(function (buttonLabel) {
md.commands.append(new Windows.UI.Popups.UICommand(buttonLabel));
});
md.showAsync().then(function (res) {
isAlertShowing = false;
var result = res ? buttons.indexOf(res.label) + 1 : 0;
if (win) {
win(result);
}
if (alertStack.length) {
setTimeout(alertStack.shift(), 0);
}
});
} catch (e) {
// set isAlertShowing flag back to false in case of exception
isAlertShowing = false;
if (alertStack.length) {
setTimeout(alertStack.shift(), 0);
}
// rethrow exception
throw e;
}
},
beep: function (winX, loseX, args) {
// set a default args if it is not set
args = args && args.length ? args : ['1'];
var snd = new Audio('ms-winsoundevent:Notification.Default'); // eslint-disable-line no-undef
var count = parseInt(args[0]) || 1;
snd.msAudioCategory = 'Alerts';
var onEvent = function () {
if (count > 0) {
snd.play();
} else {
snd.removeEventListener('ended', onEvent);
snd = null;
if (winX) {
winX(); // notification.js just sends null, but this is future friendly
}
}
count--;
};
snd.addEventListener('ended', onEvent);
onEvent();
}
};
require('cordova/exec/proxy').add('Notification', module.exports);

View File

@@ -0,0 +1,14 @@
{
"name": "cordova-plugin-dialogs-tests",
"version": "1.3.3-dev",
"description": "",
"cordova": {
"id": "cordova-plugin-dialogs-tests",
"platforms": []
},
"keywords": [
"ecosystem:cordova"
],
"author": "",
"license": "Apache 2.0"
}

View File

@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<plugin xmlns="http://apache.org/cordova/ns/plugins/1.0"
id="cordova-plugin-dialogs-tests"
version="2.0.1">
<name>Cordova Notification Plugin Tests</name>
<license>Apache 2.0</license>
<js-module src="tests.js" name="tests">
</js-module>
</plugin>

View File

@@ -0,0 +1,237 @@
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
/* eslint-env jasmine */
/* global cordova */
exports.defineAutoTests = function () {
describe('Notification (navigator.notification)', function () {
it('should exist', function () {
expect(navigator.notification).toBeDefined();
});
it('should contain a beep function', function () {
expect(typeof navigator.notification.beep).toBeDefined();
expect(typeof navigator.notification.beep).toBe('function');
});
it('should contain an alert function', function () {
expect(typeof navigator.notification.alert).toBeDefined();
expect(typeof navigator.notification.alert).toBe('function');
});
it('should contain a confirm function', function () {
expect(typeof navigator.notification.confirm).toBeDefined();
expect(typeof navigator.notification.confirm).toBe('function');
});
it('should contain a prompt function', function () {
expect(typeof navigator.notification.prompt).toBeDefined();
expect(typeof navigator.notification.prompt).toBe('function');
});
});
};
/******************************************************************************/
/******************************************************************************/
/******************************************************************************/
exports.defineManualTests = function (contentEl, createActionButton) {
var logMessage = function (message) {
var log = document.getElementById('info');
var logLine = document.createElement('div');
logLine.innerHTML = message;
log.appendChild(logLine);
};
var clearLog = function () {
var log = document.getElementById('info');
log.innerHTML = '';
};
var beep = function () {
console.log('beep()');
navigator.notification.beep(3);
};
var alertDialog = function (message, title, button) {
console.log('alertDialog()');
navigator.notification.alert(message,
function () {
console.log('Alert dismissed.');
},
title, button);
console.log('After alert');
};
var confirmDialogA = function (message, title, buttons) {
clearLog();
navigator.notification.confirm(message,
function (r) {
if (r === 0) {
logMessage('Dismissed dialog without making a selection.');
console.log('Dismissed dialog without making a selection.');
} else {
console.log('You selected ' + r);
logMessage('You selected ' + (buttons.split(','))[r - 1]);
}
},
title,
buttons);
};
var confirmDialogB = function (message, title, buttons) {
clearLog();
navigator.notification.confirm(message,
function (r) {
if (r === 0) {
logMessage('Dismissed dialog without making a selection.');
console.log('Dismissed dialog without making a selection.');
} else {
console.log('You selected ' + r);
logMessage('You selected ' + buttons[r - 1]);
}
},
title,
buttons);
};
var promptDialog = function (message, title, buttons, defaultText) {
clearLog();
navigator.notification.prompt(message,
function (r) {
if (r && r.buttonIndex === 0) {
var msg = 'Dismissed dialog';
if (r.input1) {
msg += ' with input: ' + r.input1;
}
logMessage(msg);
console.log(msg);
} else {
console.log('You selected ' + r.buttonIndex + ' and entered: ' + r.input1);
logMessage('You selected ' + buttons[r.buttonIndex - 1] + ' and entered: ' + r.input1);
}
},
title,
buttons, defaultText);
};
/******************************************************************************/
var dialogs_tests = '<div id="beep"></div>' +
'Expected result: Device will beep (unless device is on silent). Nothing will get updated in status box.' +
'<h2>Dialog Tests</h2>' +
'<h3>Dialog boxes will pop up for each of the following tests</h3>' +
'<p/> <div id="alert"></div>' +
'Expected result: Dialog will say "You pressed alert". Press continue to close dialog. Nothing will get updated in status box.' +
'<p/> <div id="confirm_deprecated"></div>' +
'Expected result: Dialog will say "You pressed confirm". Press Yes, No, or Maybe to close dialog. Status box will tell you what option you selected.' +
'<p/> <div id="confirm"></div>' +
'Expected result: Dialog will say "You pressed confirm". Press Yes, No, or Maybe, Not Sure to close dialog. Status box will tell you what option you selected, and should use 1-based indexing.' +
'<p/> <div id="prompt"></div>' +
'Expected result: Dialog will say "You pressed prompt". Enter any message and press Yes, No, or Maybe, Not Sure to close dialog. Status box will tell you what option you selected and message you entered or if empty, it will display "Default Text", and should use 1-based indexing.' +
'<p/> <div id="built_in_alert"></div>' +
'Expected result: Dialog will have title "index.html" and say "You pressed alert" Press OK to close dialog. Nothing will get updated in status box.' +
'<p/> <div id="built_in_confirm"></div>' +
'Expected result: Dialog will have title "index.html" and say "You selected confirm". Press Cancel or OK to close dialog. Nothing will get updated in status box.' +
'<p/> <div id="built_in_prompt"></div>' +
'Expected result: Dialog will have title "index.html" and say "This is a prompt". "Default value" will be in text box. Press Cancel or OK to close dialog. Nothing will get updated in status box.' +
'<p/> <h3>CB-8947 Tests</h3><div id="cb8947"></div>' +
'Expected results: Dialogs will not crash iOS';
contentEl.innerHTML = '<div id="info"></div>' +
dialogs_tests;
createActionButton('Beep', function () {
beep();
}, 'beep');
createActionButton('Alert Dialog', function () {
alertDialog('You pressed alert.', 'Alert Dialog', 'Continue');
}, 'alert');
// WP8.1 detection is necessary since it doesn't support confirm dialogs with more than 2 buttons
var isRunningOnWP81 = cordova.platformId === 'windows' && navigator.userAgent.indexOf('Windows Phone') > -1;
createActionButton('Confirm Dialog - Deprecated', function () {
var buttons = isRunningOnWP81 ? 'Yes,No' : 'Yes,No,Maybe';
confirmDialogA('You pressed confirm.', 'Confirm Dialog', buttons);
}, 'confirm_deprecated');
createActionButton('Confirm Dialog', function () {
var buttons = isRunningOnWP81 ? ['Yes', 'Actually, No'] : ['Yes', 'No', 'Maybe, Not Sure'];
confirmDialogB('You pressed confirm.', 'Confirm Dialog', buttons);
}, 'confirm');
createActionButton('Prompt Dialog', function () {
promptDialog('You pressed prompt.', 'Prompt Dialog', ['Yes', 'No', 'Maybe, Not Sure'], 'Default Text');
}, 'prompt');
createActionButton('Prompt Dialog - no default', function () {
promptDialog('You pressed prompt.', 'Prompt Dialog', ['Yes', 'No']);
}, 'prompt');
createActionButton('Built-in Alert Dialog', function () {
if (typeof alert === 'function') {
alert('You pressed alert'); // eslint-disable-line no-undef
}
}, 'built_in_alert');
createActionButton('Built-in Confirm Dialog', function () {
if (typeof confirm === 'function') {
confirm('You selected confirm'); // eslint-disable-line no-undef
}
}, 'built_in_confirm');
createActionButton('Built-in Prompt Dialog', function () {
if (typeof prompt === 'function') {
prompt('This is a prompt', 'Default value'); // eslint-disable-line no-undef
}
}, 'built_in_prompt');
// CB-8947 - ensure number messages don't crash iOS
createActionButton('Alert Dialog with Number', function () {
var callback = function () { clearLog(); console.log('Test passed'); };
navigator.notification.alert(17, callback);
}, 'cb8947');
// CB-8947 - ensure object messages don't crash iOS
createActionButton('Alert Dialog with Object', function () {
var object = { number: 42, message: "Make sure an object doesn't crash iOS", issue: 'CB-8947' };
var callback = function () { clearLog(); console.log('Test passed'); };
navigator.notification.alert(object, callback);
}, 'cb8947');
// CB-8947 - ensure object messages don't crash iOS
createActionButton('Confirm Dialog with Object', function () {
var object = { number: 42, message: "Make sure an object doesn't crash iOS", issue: 'CB-8947' };
var callback = function () { clearLog(); console.log('Test passed'); };
navigator.notification.confirm(object, callback);
}, 'cb8947');
// CB-8947 - ensure object messages don't crash iOS
createActionButton('Prompt Dialog with Object', function () {
var object = { number: 42, message: "Make sure an object doesn't crash iOS", issue: 'CB-8947' };
var callback = function () { clearLog(); console.log('Test passed'); };
navigator.notification.prompt(object, callback);
}, 'cb8947');
};

View File

@@ -0,0 +1,69 @@
// Type definitions for Apache Cordova Dialogs plugin
// Project: https://github.com/apache/cordova-plugin-dialogs
// Definitions by: Microsoft Open Technologies Inc <http://msopentech.com>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
//
// Copyright (c) Microsoft Open Technologies Inc
// Licensed under the MIT license.
interface Navigator {
/** This plugin provides access to some native dialog UI elements. */
notification: Notification
}
/** This plugin provides access to some native dialog UI elements. */
interface Notification {
/**
* Shows a custom alert or dialog box. Most Cordova implementations use a native dialog box for this feature,
* but some platforms use the browser's alert function, which is typically less customizable.
* @param message Dialog message.
* @param alertCallback Callback to invoke when alert dialog is dismissed.
* @param title Dialog title, defaults to 'Alert'.
* @param buttonName Button name, defaults to OK.
*/
alert(message: string,
alertCallback: () => void,
title?: string,
buttonName?: string): void;
/**
* The device plays a beep sound.
* @param times The number of times to repeat the beep.
*/
beep(times: number): void;
/**
* Displays a customizable confirmation dialog box.
* @param message Dialog message.
* @param confirmCallback Callback to invoke with index of button pressed (1, 2, or 3)
* or when the dialog is dismissed without a button press (0).
* @param title Dialog title, defaults to Confirm.
* @param buttonLabels Array of strings specifying button labels, defaults to [OK,Cancel].
*/
confirm(message: string,
confirmCallback: (choice: number) => void,
title?: string,
buttonLabels?: string[]): void;
/**
* Displays a native dialog box that is more customizable than the browser's prompt function.
* @param message Dialog message.
* @param promptCallback Callback to invoke when a button is pressed.
* @param title Dialog title, defaults to "Prompt".
* @param buttonLabels Array of strings specifying button labels, defaults to ["OK","Cancel"].
* @param defaultText Default textbox input value, default: "".
*/
prompt(message: string,
promptCallback: (result: NotificationPromptResult) => void,
title?: string,
buttonLabels?: string[],
defaultText?: string): void;
}
/** Object, passed to promptCallback */
interface NotificationPromptResult {
/**
* The index of the pressed button. Note that the index uses one-based indexing, so the value is 1, 2, 3, etc.
* 0 is the result when the dialog is dismissed without a button press.
*/
buttonIndex: number;
/** The text entered in the prompt dialog box. */
input1: string;
}

View File

@@ -0,0 +1,74 @@
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
var exec = require('cordova/exec');
/**
* Provides Android enhanced notification API.
*/
module.exports = {
activityStart: function (title, message) {
// If title and message not specified then mimic Android behavior of
// using default strings.
if (typeof title === 'undefined' && typeof message === 'undefined') {
title = 'Busy';
message = 'Please wait...';
}
exec(null, null, 'Notification', 'activityStart', [ title, message ]);
},
/**
* Close an activity dialog
*/
activityStop: function () {
exec(null, null, 'Notification', 'activityStop', []);
},
/**
* Display a progress dialog with progress bar that goes from 0 to 100.
*
* @param {String}
* title Title of the progress dialog.
* @param {String}
* message Message to display in the dialog.
*/
progressStart: function (title, message) {
exec(null, null, 'Notification', 'progressStart', [ title, message ]);
},
/**
* Close the progress dialog.
*/
progressStop: function () {
exec(null, null, 'Notification', 'progressStop', []);
},
/**
* Set the progress dialog value.
*
* @param {Number}
* value 0-100
*/
progressValue: function (value) {
exec(null, null, 'Notification', 'progressValue', [ value ]);
}
};

View File

@@ -0,0 +1,110 @@
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
// Platform: browser
window.navigator.notification = window.navigator.notification || {};
module.exports.alert = window.navigator.notification.alert = function (message, callback) {
// `notification.alert` executes asynchronously
setTimeout(function () {
window.alert(message);
if (callback) {
callback();
}
}, 0);
};
module.exports.confirm = window.navigator.notification.confirm = function (message, callback) {
// `notification.confirm` executes asynchronously
/* eslint-disable standard/no-callback-literal */
setTimeout(function () {
var result = window.confirm(message);
if (callback) {
if (result) {
callback(1); // OK
} else {
callback(2); // Cancel
}
}
}, 0);
};
module.exports.prompt = window.navigator.notification.prompt = function (message, callback, title, buttonLabels, defaultText) {
// `notification.prompt` executes asynchronously
setTimeout(function () {
var result = window.prompt(message, defaultText || '');
if (callback) {
if (result === null) {
callback({ buttonIndex: 2, input1: '' }); // Cancel
} else {
callback({ buttonIndex: 1, input1: result }); // OK
}
}
}, 0);
};
/* eslint-enable standard/no-callback-literal */
var audioContext = (function () {
// Determine if the Audio API is supported by this browser
var AudioApi = window.AudioContext;
if (!AudioApi) {
AudioApi = window.webkitAudioContext;
}
if (AudioApi) {
// The Audio API is supported, so create a singleton instance of the AudioContext
return new AudioApi();
}
return undefined;
}());
module.exports.beep = window.navigator.notification.beep = function (times) {
if (times > 0) {
var BEEP_DURATION = 700;
var BEEP_INTERVAL = 300;
if (audioContext) {
// Start a beep, using the Audio API
var osc = audioContext.createOscillator();
osc.type = 0; // sounds like a "beep"
osc.connect(audioContext.destination);
osc.start(0);
setTimeout(function () {
// Stop the beep after the BEEP_DURATION
osc.stop(0);
if (--times > 0) {
// Beep again, after a pause
setTimeout(function () {
navigator.notification.beep(times);
}, BEEP_INTERVAL);
}
}, BEEP_DURATION);
} else if (typeof (console) !== 'undefined' && typeof (console.log) === 'function') {
// Audio API isn't supported, so just write `beep` to the console
for (var i = 0; i < times; i++) {
console.log('Beep!');
}
}
}
};

View File

@@ -0,0 +1,130 @@
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
var exec = require('cordova/exec');
var platform = require('cordova/platform');
/**
* Provides access to notifications on the device.
*/
module.exports = {
/**
* Open a native alert dialog, with a customizable title and button text.
*
* @param {String} message Message to print in the body of the alert
* @param {Function} completeCallback The callback that is called when user clicks on a button.
* @param {String} title Title of the alert dialog (default: Alert)
* @param {String} buttonLabel Label of the close button (default: OK)
*/
alert: function (message, completeCallback, title, buttonLabel) {
var _message = (typeof message === 'string' ? message : JSON.stringify(message));
var _title = (typeof title === 'string' ? title : 'Alert');
var _buttonLabel = (buttonLabel && typeof buttonLabel === 'string' ? buttonLabel : 'OK');
exec(completeCallback, null, 'Notification', 'alert', [_message, _title, _buttonLabel]);
},
/**
* Open a native confirm dialog, with a customizable title and button text.
* The result that the user selects is returned to the result callback.
*
* @param {String} message Message to print in the body of the alert
* @param {Function} resultCallback The callback that is called when user clicks on a button.
* @param {String} title Title of the alert dialog (default: Confirm)
* @param {Array} buttonLabels Array of the labels of the buttons (default: ['OK', 'Cancel'])
*/
confirm: function (message, resultCallback, title, buttonLabels) {
var _message = (typeof message === 'string' ? message : JSON.stringify(message));
var _title = (typeof title === 'string' ? title : 'Confirm');
var _buttonLabels = (buttonLabels || ['OK', 'Cancel']);
// Strings are deprecated!
if (typeof _buttonLabels === 'string') {
console.log('Notification.confirm(string, function, string, string) is deprecated. Use Notification.confirm(string, function, string, array).');
}
_buttonLabels = convertButtonLabels(_buttonLabels);
exec(resultCallback, null, 'Notification', 'confirm', [_message, _title, _buttonLabels]);
},
/**
* Open a native prompt dialog, with a customizable title and button text.
* The following results are returned to the result callback:
* buttonIndex Index number of the button selected.
* input1 The text entered in the prompt dialog box.
*
* @param {String} message Dialog message to display (default: "Prompt message")
* @param {Function} resultCallback The callback that is called when user clicks on a button.
* @param {String} title Title of the dialog (default: "Prompt")
* @param {Array} buttonLabels Array of strings for the button labels (default: ["OK","Cancel"])
* @param {String} defaultText Textbox input value (default: empty string)
*/
prompt: function (message, resultCallback, title, buttonLabels, defaultText) {
var _message = (typeof message === 'string' ? message : JSON.stringify(message));
var _title = (typeof title === 'string' ? title : 'Prompt');
var _buttonLabels = (buttonLabels || ['OK', 'Cancel']);
// Strings are deprecated!
if (typeof _buttonLabels === 'string') {
console.log('Notification.prompt(string, function, string, string) is deprecated. Use Notification.confirm(string, function, string, array).');
}
_buttonLabels = convertButtonLabels(_buttonLabels);
var _defaultText = (defaultText || '');
exec(resultCallback, null, 'Notification', 'prompt', [_message, _title, _buttonLabels, _defaultText]);
},
/**
* Causes the device to beep.
* On Android, the default notification ringtone is played "count" times.
*
* @param {Integer} count The number of beeps.
*/
beep: function (count) {
var defaultedCount = count || 1;
exec(null, null, 'Notification', 'beep', [ defaultedCount ]);
}
};
function convertButtonLabels (buttonLabels) {
// Some platforms take an array of button label names.
// Other platforms take a comma separated list.
// For compatibility, we convert to the desired type based on the platform.
if (platform.id === 'amazon-fireos' || platform.id === 'android' || platform.id === 'ios' ||
platform.id === 'windowsphone' || platform.id === 'firefoxos' || platform.id === 'ubuntu' ||
platform.id === 'windows8' || platform.id === 'windows') {
if (typeof buttonLabels === 'string') {
buttonLabels = buttonLabels.split(','); // not crazy about changing the var type here
}
} else {
if (Array.isArray(buttonLabels)) {
var buttonLabelArray = buttonLabels;
buttonLabels = buttonLabelArray.toString();
}
}
return buttonLabels;
}

View File

@@ -0,0 +1,84 @@
/*
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
.dlgWrap {
position: absolute;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.25);
z-index: 100000;
top: 0;
}
.dlgContainer {
width: 100%;
min-height: 180px;
height: auto;
overflow: auto;
background-color: white;
position: relative;
line-height: 2;
top: 50%;
transform: translateY(-50%);
padding: 0 30%;
}
.dlgContainer #lbl-title {
font-size: 24pt;
}
.dlgContainer #prompt-input {
width: 100%;
}
.dlgButton {
margin: 8px 0 0 16px;
float: right;
font-size: 11pt;
background-color: #cccccc;
border: none;
font-weight: 600;
font-family: "Segoe UI", Arial, sans-serif;
padding: 0 22px;
}
.dlgButton.dlgButtonFirst {
color: white;
background-color: #464646;
}
.dlgContainer.dlgContainer-windows {
width: 50%;
max-width: 680px;
padding: 0 5%;
top: 50%;
left: 50%;
position: fixed;
transform: translate(-50%, -50%);
border: 1px solid rgb(24, 160, 191);
border-image: none;
box-shadow: 0 0 14px 6px rgba(0,0,0,0.16);
text-transform: none;
}
.dlgContainer.dlgContainer-phone {
padding: 0 5%;
}