I have a dialog to show to user an input type file. I have an issue when the user canceled the input file or when he chooses the same file, that closes my dialog. I don’t want that, so I added event Listener ‘cancel’ with event prevent default. But that didn’t work.
<button id="openDialogButton">Open dialog</button>
<dialog id="dialog">
<h1>Hi, I'm a dialog !</h1>
<input type='file'>
<p><button id="closeDialogButton">Close dialog</button></p>
</dialog>
const buttonOpen = document.querySelector("#openDialogButton");
const buttonClose = document.querySelector("#closeDialogButton");
const dialog = document.querySelector("#dialog");
buttonOpen.addEventListener("click", (e) => {
dialog.showModal();
});
buttonClose.addEventListener("click", (e) => {
dialog.close();
});
dialog.addEventListener("cancel", (e) => {
console.log(e);
e.preventDefault();
});
codepen here : https://codepen.io/catif/pen/LYgKNmN
2
Answers
After the comment of Simone Rossaini, I tried on Firefox, Edge, Opera and Chrome.
All Chromium's browsers didn't work, and that already a bug reported on Chromium => https://bugs.chromium.org/p/chromium/issues/detail?id=1449848
It seems that preventing the dialog from closing when you cancels/add same file selection is not directly achievable with the current dialog implementation.
One alternative solution is to create a custom dialog using HTML and CSS, and handle the file selection logic manually.