且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Modernizr支持的链接中检测数据URI

更新时间:2021-07-21 09:26:20

我对特征检测的需求相同,但是我没有使用Modernizr.我的用例是,我正在使用makePDF库在客户端生成pdf,而无法使用IE或Edge中的数据URI打开PDF.不幸的是,我可以找到的所有功能检测脚本都在测试是否支持图像的数据URI(MS浏览器支持),因此我必须编写自己的脚本.这是代码(感谢上面的BoltClock的注释):

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()

我在IE 11,Edge 25,Firefox 46和Chrome 49中进行了测试.

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

作为旁注,另一个SO答案( https://***.com/a/26003382/634650 )建议使用:

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

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

这在IE中有效,但在Edge中无效.

This works in IE but not Edge.

上面的SO答案还包含指向 SO答案的链接. .com/Modernizr/Modernizr/issues/1190"rel =" nofollow noreferrer>有关iframe支持中数据URI特征检测的Modernizr问题.在iframe中打开数据URI基本上与在新窗口中打开数据URI相同,并且在iframe中不支持数据URI的Microsoft浏览器不支持在新窗口中打开它们.此外,在这些位置提到的iframe支持测试是同步的,因此我建议使用它代替我的异步解决方案.

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.