如何在“窗口”之间进行选择.URL.createObjectURL()' 和 'window.webkitURL.cre

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

本文关键字:cre webkitURL window createObjectURL URL 窗口 之间 选择 行选      更新时间:2023-09-26

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

objectURL = window.URL.createObjectURL(file);

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

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

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

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

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

然后:

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

简单的一行:

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

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

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