Search code examples
javascriptsafaricross-browserdata-transfer

How can I reliably determine if a browser supports the DataTransfer() constructor?


I have a file uploader that uses new DataTransfer() to generate and display thumbnails for uploaded images. For Safari users, this constructor is not supported. The tricky part is that DataTransfer as a feature is supported - it's specifically the constructor that is not.

How can I detect if this feature exists, so that I can provide a standard file input for Safari users? To clarify, I'm not looking for help with the fallback - just the feature detection itself.

I attempted the following to no avail:

const isConstructor = (func) => (func && typeof func === "function" && func.prototype && func.prototype.constructor) === func;

isConstructor(DataTransfer);  //true in Safari

Solution

  • I was able to work around this, but in a somewhat hacky fashion that I'm not quite happy with. I'll still take any better answers I can get.

    let dataTransferConstructorSupported = false;
    try { new DataTransfer(), dataTransferConstructorSupported = true } catch {}
    
    console.log(dataTransferConstructorSupported);