Javascript 如何根据浏览器在`window.URL.createObjectURL()`和`window.webkitURL.createObjectURL()`之间进行选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11277677/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 05:14:47  来源:igfitidea点击:

How to choose between `window.URL.createObjectURL()` and `window.webkitURL.createObjectURL()` based on browser

javascripthtmldom

提问by Rohith Raveendran

From the Firefox developer website, I know that Firefox uses

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

objectURL = window.URL.createObjectURL(file);

to get url of file type, but in chrome and other webkit browsers we have window.webkitURL.createObjectURL()for detecting url.

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

I don't know how to swap this functions based on browser engines, and I need it to be worked on both browsers (Chrome and firefox)

我不知道如何根据浏览器引擎交换这个功能,我需要它在两个浏览器(Chrome 和 firefox)上都能工作

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

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

回答by Trevor

Simple one liner:

简单的一个班轮:

var createObjectURL = (window.URL || window.webkitURL || {}).createObjectURL || function(){};

回答by ?ime Vidas

You could define a wrapper function:

您可以定义一个包装函数:

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;
    }
}

And then:

进而:

// works cross-browser
var url = createObjectURL( file );

回答by 65Fbef05

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

Is round-about what you're looking for. Also, THISexample uses the much simpler...

是你正在寻找的东西。此外,这个例子使用了更简单的......

window.URL = window.URL || window.webkitURL;