Okienka dialogowe

UWAGA: Tłumaczenie tej strony nie zostało zakończone.
Może być ona niekompletna lub wymagać korekty.
Chcesz pomóc? | Dokończ tłumaczenie | Sprawdź ortografię | Więcej takich stron+.
Strona ta posiada fragmenty kodu stosowane do wyświetlenia i okienka podczas wykonywania procesu w pudełku. Zobacz Working with windows in chrome code, aby uzyskać więcej informacji, dyskusji i przykładów.

Opisywanie okienek dialogowych

Okienka dialogowe w Mozilli

Whenever you want to create a dialog in your application, use <dialog> (instead of usual <window>) as root element in the XUL file. This will:

  • Handle a few keyboard events (ENTER/ESC and more), which is good for keyboard accessibility.
  • Add OK and Cancel buttons in an order that is consistent with OS default (but the button set and layout is highly customizable, see below).

Prosty kod okienka dialogowego

The following XUL code defines a simple dialog with two buttons, OK and Cancel (buttons="accept,cancel" attribute on dialog).

<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/global.css" type="text/css"?>

<dialog xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
	id="..." title="..."
	ondialogaccept="return onAccept();"
	ondialogcancel="return onCancel();">

<script src="chrome://..."/>

<!-- Content -->


You need to implement onAccept and onCancel functions in your script. If they return anything but false, the dialog will be closed.

Przyciski w <dialog>


There are six button types you can use in the buttons attribute of dialog. They are:

For each of these buttons you can set their label, accesskey and oncommand handler by adding buttonlabel<buttonname>, buttonaccesskey<buttonname> and ondialog<buttonname> attributes to the dialog element. For example, to add an an Apply button to your dialog, use the following code:

<dialog xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" 

<!-- Content -->

You can even get the element object for any of predefined buttons with <tt>gDialog.getButton(dlgtype);</tt>, where gDialog is the <dialog> element and dlgtype is one of the six button types listed above.


If you are not satisfied with the layout of predefined buttons in dialog, you can put explicit button elements in your XUL file and add a dlgtype attribute to them. Valid values for dlgtype are the six button types listed above.

Be sure to use ondialog* attributes on dialog element instead of putting oncommand on the button with dlgtype, because button's oncommand is executed only when the button is pressed, and ondialog* handlers are executed for keyboard and other events too.


<?xml version="1.0"?>
<?xml-stylesheet href="chrome://global/skin/" type="text/css"?>

<dialog xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"
  <label value="Hey!"/>

  <spacer flex="1"/>
    <button dlgtype="accept"/>
    <button dlgtype="cancel"/>
Domyślny przycisk

Since Firefox 1.5, there are defaultButton attribute and property on the <dialog> element . The possible values for the attribute are the names of buttons listed above, and the default is "accept", for compatibility with previous versions.

Zastosowanie <dialogheader>

You can use the dialogheader element to add "headers" to windows. To get an idea of what it looks like, open Options (or Preferences) dialog in Firefox or Thunderbird ( v1.0 and earlier only ). The header to the right of the sections buttons is made with <dialogheader>:

<dialogheader title="General" description="whatever"/>

Note, that you should only use this element in a <dialog>, because otherwise it may be not styled properly. (Although it seems to work in <window> as well).


Passing arguments and displaying a dialog

The following code demonstrate how to pass custom arguments to a dialog, process those arguments in the dialog, and return user-modified arguments to the caller. The code to open a dialog named mydialog.xul and pass it arguments:

var params = {inn:{name:"foo", description:"bar", enabled:true}, out:null};       
  window.openDialog("chrome://myext/chrome/mydialog.xul", "",
    "chrome, dialog, modal, resizable=yes", params).focus();
  if (params.out) {
    // User clicked ok. Process changed arguments; e.g. write them to disk or whatever
  else {
    // User clicked cancel. Typically, nothing is done here.


  title="My Dialog"
  ondialogaccept="return onOK();"
  persist="screenX screenY width height"

  <script type="application/x-javascript" src="chrome://myext/content/mydialog.js"/>
      <row align="center"><label value="Name:"/><textbox id="name"/></row>
      <row align="center"><label value="Description:"/><textbox id="description"/></row>
      <row align="center"><spacer/><checkbox id="enabled" label="Check to Enable"/></row>


// Called once when the dialog displays
function onLoad() {
  // Use the arguments passed to us by the caller
  document.getElementById("name").value = window.arguments[0].inn.name;
  document.getElementById("description").value = window.arguments[0].inn.description;
  document.getElementById("enabled").checked = window.arguments[0].inn.enabled;

// Called once if and only if the user clicks OK
function onOK() {
   // Return the changed arguments.
   // Notice if user clicks cancel, window.arguments[0].out remains null
   // because this function is never called
   window.arguments[0].out = {name:document.getElementById("name").value,
   return true;

See also Passing parameter to a dialog and getting return values from it.

Displaying the standard "Open File"/"Save File"/"Select Folder" dialogs


Prompts and the prompt service

Now that you understand dialogs, let's examine prompts. Prompts differ from dialogs in that they don't require custom XUL. Because of this, however, they are less customizable. Most web developers are familiar with the alert() function:


This is a prime example of a prompt.

nsIPromptService is an XPCOM interface available to C++ and chrome JavaScript code (not to web pages' JS), that provides methods for displaying a few simple types of dialogs.

For file/folder picker dialogs, see nsIFilePicker.

nsIPromptService has 9 functions and a few constants that are important to understand. This article contains explanations for some of these functions, and example code for all of them.

Getting nsIPromptService

First of all, you need to obtain the prompt service which you can use to show messages. You can do this using the following code:

var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]

nsIPromptService methods


alert() is the simplest function, which simply displays a message box with specified title and message. For example:

var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
prompts.alert(window, "Window title", "Hello world!");

As in many other methods of nsIPromptService, first parameter is the parent window in the sense of nsIWindowWatcher.openWindow. You can pass null, in which case the parent window will be nsIWindowWatcher.activeWindow.


alertCheck() will popup a message box with specified title, text and a checkbox. The checkbox can be a "Do not show this message again" option or something similar.

var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
check = {value: false}; // default value
prompts.alertCheck(window, "Window title", "You have been warned", 
                   "Don't ask again", check);
// do something with check.value;

Notice how we get the state of the checkbox. The function changes the value member of the check object, so to get the result we use check.value. It's the standard way of getting so-called "out" parameters from an XPCOM component.

confirm() i confirmCheck()

confirm() jest także prosty. It displays a dialog with specified title, text and two buttons - OK and Cancel.

var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
var result = prompts.confirm(window, "Title", "Do you want to quit?");

Below is an example for displaying a confirmation message with a checkbox. It is a hybrid of confirm() and alertCheck(), so it should be easy to understand without additional comments.

var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
var check = {value: false};
var result = prompts.confirmCheck(window, "Title", "Do you want to quit?", 
                                  "Do not ask me again", check);
// do something check.value / result

prompt() can be very important and useful in lots of cases, as it accepts user input. Instead of making an XUL dialog or adding more textboxes you can simply call a prompt function. As you can see the first few arguments are the same as the others but it has an extra object. This object is the default value before the function is called and the new value after the function has been called.

var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
var input = {value: "default value"};
var check = {value: false};
result = prompts.prompt(window, "Title", "What's your name?", input, "Do not ask again", check);
// input.value is the string user entered
// check.value indicates whether or not the checkbox is checked
// result - whether user clicked OK (true) or Cancel
promptPassword() i promptUsernameAndPassword()

Below are other versions of prompt, promptPassword() with a password textbox and promptUsernameAndPassword() which has a username and password field.

var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
input = {value:"password"};
check = {value:false};
okorcancel = prompts.promptPassword(window, 'title', 'Text', input, 'Check?', check);
return input.value;
return check.value;
return okorcancel;

var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
username = {value:"ihoss"};
password = {value:"password"};
check = {value:false};
okorcancel = prompts.promptUsernameAndPassword(window, 'title', 'Text', username, password, 'Check?', check);
return username.value;
return password.value;
return check.value;
return okorcancel;
var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
var check = {value: false};
var flags = 0;
var button = prompts.confirmEx(window, "Window title", "Message text", flags, 
             "Button 0", "Button 1", "Button 2", "Checkbox label", check);
// |check.value| indicates whether or not the checkbox is checked
// |button| indicates which button was clicked

confirmEx() is designed to be customizable so you can make your own messages. It can display a dialog with up to 3 buttons with a variety of predefined (localized if necessary) labels or specified by your code labels, and a checkbox if you want. If you don't want the checkbox to be displayed, just put null in the eighth (checkbox label) parameter.

flags is a set of flags that indicates which buttons the dialog should display. Each button is specified as a button title flag multiplied by a button position flag:

Button Position Flags Button Title Flags

Buttons can use one of the predefined titles. Alternatively, if BUTTON_TITLE_IS_STRING is specified for a button, then the string parameter for that button will be used.

flags is formed by summing the buttons' values.

The order in which the buttons appear is platform-dependent. Button 0 is selected by default unless a button default flag is added to flags:

Button Default Flags

For example, flags as specified below causes the dialog to have a Save button, a Cancel button, and a third button whose title is the seventh argument to confirmEx() ("Button 2" in the snippet above).

var flags = prompts.BUTTON_TITLE_SAVE      * prompts.BUTTON_POS_0 +
            prompts.BUTTON_TITLE_CANCEL    * prompts.BUTTON_POS_1 +
            prompts.BUTTON_TITLE_IS_STRING * prompts.BUTTON_POS_2;

Setting flags to STD_OK_CANCEL_BUTTONS or STD_YES_NO_BUTTONS provides a shorthand to select the standard set of OK/Cancel or Yes/No buttons.


select() displays a dialog with a listbox and OK/Cancel buttons. The listbox contains specified options, and user can select exactly one of them. selected.value will get the index of the item user selected and you can get its value with list[selected.value] The 4th parameter is the number of entries you want to be displayed, it must be less than or equal to the length of the list array. If it is less then only the items up to that index will be shown in the listbox.

var prompts = Components.classes["@mozilla.org/embedcomp/prompt-service;1"]
var list = ["ihoss", "internet", "firefox", "xul", "stupid entry", "out of ideas"]
var selected = {};
var ok = prompts.select(window, "Window title", "Prompt text", 
                        list.length, list, selected);
// selected.value contains the index
// |ok| indicates whether OK or Cancel button was pressed
Wersja oryginalna

The original version of this tutorial can be found here.




Autorzy i etykiety dokumentu

Autorzy tej strony: Ptak82, splewako, Mgjbot
Ostatnia aktualizacja: splewako,