如何在基于浏览器的`window.URL.createObjectURL()`和`window.webkitURL.createObjectURL()`之间进行选择

Roh*_*ran 14 javascript html5 dom

从Firefox开发者网站,我知道Firefox使用

objectURL = window.URL.createObjectURL(file);
Run Code Online (Sandbox Code Playgroud)

获取文件类型的URL,但在chrome和其他webkit浏览器中我们有window.webkitURL.createObjectURL()检测url.

我不知道如何基于浏览器引擎交换这些功能,我需要在两种浏览器上工作(Chrome和firefox)

https://developer.mozilla.org/en/DOM/window.URL.createObjectURL

Tre*_*vor 26

简单的一个班轮:

var createObjectURL = (window.URL || window.webkitURL || {}).createObjectURL || function(){};
Run Code Online (Sandbox Code Playgroud)


Šim*_*das 24

您可以定义包装函数:

function createObjectURL ( file ) {
    if ( window.webkitURL ) {
        return window.webkitURL.createObjectURL( file );
    } else if ( window.URL && window.URL.createObjectURL ) {
        return window.URL.createObjectURL( file );
    } else {
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后:

// works cross-browser
var url = createObjectURL( file );
Run Code Online (Sandbox Code Playgroud)

  • 我认为这不再是必要了,因为当我在代码Chrome中使用它时,返回"webkitURL"已被弃用.请改用"URL".控制台中的消息. (4认同)

65F*_*f05 9

if (window.URL !== undefined) {
    window.URL.createObjectURL();
} else if (window.webkitURL !== undefined) {
    window.webkitURL.createObjectURL();
} else {
    console.log('Method Unavailable: createObjectURL');
}
Run Code Online (Sandbox Code Playgroud)

是关于你正在寻找什么.此外,这个例子使用更简单...

window.URL = window.URL || window.webkitURL;
Run Code Online (Sandbox Code Playgroud)