Input File Cancel?
Can one detect an input file cancel on the web?
by David Iglesias
HTML
<input type="file" id="file-input" />
<pre id="output"></pre>
JavaScript
function log(text) {
document.querySelector("#output").innerText += text + "\n";
}
const fileInput = document.querySelector('#file-input');
let focusSubscription;
function guardFocus(element) {
console.log('Guarding through focus...');
element.addEventListener('focus', () => triggerCancel(element), true);
}
let timeoutId;
function triggerCancel(fileInput) {
timeoutId = window.setTimeout(() => {
stopGuard(fileInput);
throw "The user canceled the selection!";
}, 100);
}
function stopGuard(fileInput) {
fileInput.removeEventListener('focus', triggerCancel, true);
window.clearTimeout(timeoutId);
}
fileInput.addEventListener('click', (event) => {
guardFocus(fileInput);
});
fileInput.addEventListener('change', (event) => {
stopGuard(fileInput);
console.log(fileInput.files);
});