5

I am using Google Chrome's folder upload feature in my project, described here: How do I use Google Chrome 11's Upload Folder feature in my own code?

I have a button that trigger an input field when be clicked. My question is How can I check if the browser support webkitdirectory or not? so I can hide my button or alert the user to use chrome for this service.

<button>Upload Folder</button>
<input type="file" name="file[]" multiple webkitdirectory>

<script>
  $("button").click(function(e) {
    /* TODO: Detect webkitdirectory support */
    if(webkitdirectory)
      $('input').trigger('click');
    else
      alert('Use Chrome!');
  });
</script>
Community
  • 1
  • 1
Hafez Divandari
  • 8,381
  • 4
  • 46
  • 63
  • I used https://github.com/DamonOehlman/detect-browser I'm not the creator, but I enjoy it because it's lightweight and does exactly what you're looking for. When used in combination with https://caniuse.com/#feat=input-file-directory makes things pretty simple. – Weeks Aug 09 '18 at 19:58
  • You could try Modernizr. Looks like they implemented a check for this a couple of years ago https://github.com/Modernizr/Modernizr/issues/674 Failing that, check out the following post https://stackoverflow.com/questions/12169585/how-to-detect-directory-select-capability-in-browsers – no1spirite Aug 31 '14 at 08:33

2 Answers2

2

To see if webkitdirectory is supported, check for the property in the input element:

webkitdirectorySupported(){
  return 'webkitdirectory' in document.createElement('input')
}
Kim Nyholm
  • 1,055
  • 1
  • 10
  • 19
  • 1
    Honestly I don't understand the reason for the downvote of this answer. The Modernizer approach seems excessively defensive and encourages the idea of browser-specific prefixes, especially since I have never encountered any other version than `webkitdirectory` so far. In any case, for defensive coding, I would simply add the check for `directory` on this answer and keep it a one-liner. Much cleaner. – Valeriu Paloş Jan 12 '22 at 03:01
1

Based on Modernizer and this answer I could use this function to detect if directory select is supported:

function testFileInputDirectory() {
    var elem = document.createElement('input'),
    dir = 'directory',
    domPrefixes = [ "", "moz", "o", "ms", "webkit" ],
    prefix;
    
    elem.type = 'file';
    
    for (prefix in domPrefixes) {
      if (domPrefixes[prefix] + dir in elem) {
        return true;
      }
    }
    return false;
}
Hafez Divandari
  • 8,381
  • 4
  • 46
  • 63