Table of Contents
Customizing JavaScript Dialogs

Event JSDialog is raised when the JavaScript engine needs to display a dialog. There are four types of dialogs:

  • Alert. This is the dialog used to handle JavaScript "window.alert" call. A typical implementation would display a message box with an "OK" button;
  • Prompt. This is the dialog used to handle JavaScript "window.prompt" call. A typical implementation would display a dialog box with a textbox for user to enter something, also an "OK" and/or "Cancel" button to accept/discard user input;
  • Confirm. This is the dialog used to handle JavaScript "window.confirm" call. A typical implementation would display a message box with a "Yes" and a "No" button;
  • BeforeUnload. This is the dialog used to confirm whether user indeed wishes to leave or close the current page when "window.onbeforeunload" event has been set by JavaScript. A typical implementation would display a message box with a "Yes" and a "No" button;

If you do not handle this event, the default implementation will be used. If you do handle this event, you can display a dialog according to JSDialogEventArgs's DialogType property. Inside your dialog, you can call the event argument's OK method or Cancel to notify the browser engine that the user has confirmed or cancelled the corresponding action.

The following code demonstrates how to use this event:

void WebView_JSDialog(object sender, JSDialogEventArgs e)
{
    switch (e.DialogType)
    {
        case JSDialogType.Prompt:
            //Create a dialog
            JSPrompt dlg = new JSPrompt(e);
            dlg.Owner = this;
            dlg.Message = e.MessageText;
            dlg.Value = e.DefaultPromptText;

            //Display the dialog for user input
            Nullable<bool> result = dlg.ShowDialog();

            //Call e.OK/e.Cancel based on whether user clicked "OK" in the dialog
            if (result.HasValue && !result.Value)
                e.OK(dlg.Value);
            else
                e.Cancel();
            break;

        case JSDialogType.Alert:
            //Display a message box and then call e.OK to notify the browser
            //engine that user has confirmed the dialog. This is important
            //because either OK or Cancel must be called to prevent the default
            //dialog
            MessageBox.Show(e.MessageText, "JavaScript Message", MessageBoxButton.OK);
            e.OK();
            break;

        case JSDialogType.BeforeUnload:
        case JSDialogType.Confirm:
            //Display a Yes/No message box and call e.OK/e.Cancel according
            //to user's selection
            if (MessageBox.Show(e.MessageText, "JavaScript Message", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                e.OK();
            else
                e.Cancel();
            break;
    }
}