“On file dialog cancel” event in JavaScript

后端 未结 2 1910
野趣味
野趣味 2021-01-17 16:01

I have a file input:


Function \'foo\' is called only when user chooses some f

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-17 16:43

    There's no event (only fires the change/input event if you have one file already selected when you click on it, because it changes to zero selected items) so this don't really answer your question. Right now the only thing I can think of is to take advantage of dialogs that open when you click the button.

    The current behavior (as I checked in Chrome) is to lose the window focus when the input is clicked and the dialog is shown, and is impossible to get again the focus on the window because when you try to do so, you get the focus on the dialog. To get the focus on the window you need to close the dialog by force. With all this we can hack something like this:

    const input = document.getElementById('inp');
    
    let timeout = null;
    let dialogopen = false;
    function checkFiles() {
      dialogopen = false;
      console.log("File count:", input.files.length);
    }
    input.addEventListener('change', (event) => {
      clearTimeout(timeout);
      checkFiles();
    });
    input.addEventListener('click', (event) => {
      clearTimeout(timeout);
      dialogopen = true;
    });
    window.addEventListener('focus', (event) => {
      if (dialogopen) {
        clearTimeout(timeout);
        timeout = setTimeout(checkFiles, 100);
      }
    });
    Click me: 

    Maybe this helps someone in the future.

提交回复
热议问题