HTML dialog tag and modal window for Electron
To replace prompt() or other dialog, a simple HTML tag.
The HTML <dialog> tag is currently (April 2017) implemented only in Chrome. So not usable in a Web application, but for Electron, it's different...
In a previous article, we saw how to replace the prompt() dialog, absent in Electron, by BrowserWindows. This works in ipcMain, but it would be simpler if we had a solution in ipcRenderer, so directly in the code of the interface of the application. With the new <dialog> tag, you can just create a modal dialog in HTML.
This will always be asynchronous as the processing does not stop at the creation point of the dialog box. But it blocks interaction with the user until it is closed, so it is modal, which is required if the processing depends on the response of the user.
The source code of the dialog is simple ...
<dialog id="pDialog">
<label for="pAnswer" id="pLabel">Default label:</label>
<input id="pAnswer" type="text" value="">
<menu>
<button onclick="pDialog.close('')">Cancel</button>
<button onclick="pDialog.close(document.getElementById('pAnswer').value)">OK</button>
</menu>
</dialog>
The close dialog method returns a value given by the program. In this case, when the user clicks the OK button, we return what he typed in the input field.
When the user clicks the Cancel button, an empty string is returned.
We then define the function that will replace the prompt() command:
function promptDialog(question, cb) {
var pDialog = document.getElementById('pDialog')
var fe = function(e) {
cb(pDialog.returnValue)
pDialog.removeEventListener("close", fe)
}
document.getElementById("pLabel").innerHTML = question
var x = pDialog.showModal()
pDialog.addEventListener('close', fe)
}
The first parameter is the label of the box, which corresponds to the question to which the user must give a response.
The second parameter is a callback, necessary because dialog is asynchronous, and is used to return the response.
We open the box with the showModal() method. Then the value given as a parameter to the close() method is retrieved using a listener and the returnValue attribute of dialog.
This replacement prompt is used with a function call:
promptDialog("My own label:", function(x) {
if(x != '')
alert(x)
})
Replace alert(x) by your application's own code ...
The complete code of the demo is available in an archive:
To start the demo, type: electron dialog.js
This code can be generalized for all kinds of dialog boxes and actually makes dialog.showMessageBox() obsolete.
This dialog box is used by Advanced Explorer since the version 4.3 to copy/rename and create a new directory.