Detect data URI in links support with Modernizr

2019-05-04 11:37发布

问题:

Using data URI in links (<a href="data:) is not supported in IE and Microsoft Edge (Data URI link <a href="data: doesn't work in Microsoft Edge).

I'm trying to use Modernizr to detect data URI in links support.

Modernizr.datauri is not quite what I'm looking for, as it does not tell anything about support data URI in links, e.g. for Microsoft Edge it returns object {over32kb: true}

How can I detect using Modernizr if data URI in links is supported in browser?

回答1:

I had the same need for feature detection but I am not using Modernizr. My use case is that I'm generating a pdf on the client side with the makePDF library and was not able to open the PDFs using data URIs in IE or Edge. Unfortuantely, all the feature detection scripts I could find were testing for support of data URIs for images (which is supported by MS browsers) so I had to write my own. Here's the code (thanks to BoltClock's comment above for the idea):

checkDataURISupport(function (checkResult) {
    if (checkResult) {
        alert('Files in data URIs are supported.');
    } else {
        alert('Files in data URIs are NOT supported.');
    }
})

function checkDataURISupport(callback) {
    try {
        var request = new XMLHttpRequest();
        request.onload = function reqListener() {
            callback(true);
        };
        request.onerror = function reqListener() {
            callback(false);
        };
        request.open('GET', 'data:application/pdf;base64,cw==');
        request.send();
    } catch (ex) {
        callback(false);
    }
}

checkDataURISupport()

I tested in in IE 11, Edge 25, Firefox 46, and Chrome 49.

As a side note, another SO answer (https://stackoverflow.com/a/26003382/634650) suggested using:

supportsDataUri = 'download' in document.createElement('a');

This works in IE but not Edge.

Update

The SO answer above also includes a link to a SO answer referencing a Modernizr issue about feature detection for data URI in iframe support. Opening a data URI in an iframe is basically the same thing as opening one in a new windows and the Microsoft browsers which do not support data URIs in iframes don't support opening them in new windows. Additionally, the test for the iframe support mentioned in those locations is synchronous so I would recommend using it instead of my async solution.



回答2:

It is weird that even Microsoft Edge is not supporting the data URI. Older versions of IE only allows base64 encoded images of up to 32KB. I had come across a reference link lately which relates to the similar issue you have mentioned with Moderinzr.

Does modernizr check for data uri's?#294

It appears they have added a patch for the issue. It is a data URI test.

This post has the similar answer regarding the issue. I hope these fixes should work throughout.